gh-89263: Add typing.get_overloads by JelleZijlstra · Pull Request #31716 · python/cpython (original) (raw)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I have a few thoughts.

Overall, I guess I'm a little concerned about "dumping" so many new functions in the global functools namespace. functools is already kind of a hodgepodge of unrelated things, and I worry that this will make the problem worse.

Normally I'd say that having a class with 0 instance methods would be a code smell, but what about something like this?

class VariantRegistry: _registry = defaultdict(list)

@staticmethod
def _get_key_for_callable(func):
    func = getattr(func, "__func__", func)
    try:
        return f"{func.__module__}.{func.__qualname__}"
    except AttributeError:
        return None

@classmethod
def register_variant(func, variant):
    key = cls._get_key_for_callable(func)
    if key is not None:
        cls._variant_registry[key].append(variant)

@classmethod
def get_variants(cls, func):
    return cls._registry[cls._get_key_for_callable(func)]

@classmethod
def clear_variants(cls, func=None):
    if func is None:
       cls._variant_registry.clear()
    else:
        cls._variant_registry.pop(cls._get_key_for_callable(func), None)