Skip to content

Reference

multimethod.multimethod

Bases: dict

A callable directed acyclic graph of methods.

Source code in multimethod/__init__.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
class multimethod(dict):
    """A callable directed acyclic graph of methods."""

    __name__: str
    pending: set
    generics: list[tuple]  # positional bases which require instance checks

    def __new__(cls, func):
        homonym = inspect.currentframe().f_back.f_locals.get(func.__name__)
        if isinstance(homonym, multimethod):
            return homonym

        self = functools.update_wrapper(dict.__new__(cls), func)
        self.pending = set()
        self.generics = []
        return self

    def __init__(self, func: Callable):
        try:
            self[signature.from_hints(func)] = func
        except (NameError, AttributeError):
            self.pending.add(func)

    @tp_overload
    def register(self, __func: REGISTERED) -> REGISTERED: ...  # pragma: no cover

    @tp_overload
    def register(self, *args: type) -> Callable[[REGISTERED], REGISTERED]: ...  # pragma: no cover

    def register(self, *args) -> Callable:
        """Decorator for registering a function.

        Optionally call with types to return a decorator for unannotated functions.
        """
        if len(args) == 1 and hasattr(args[0], '__annotations__'):
            multimethod.__init__(self, *args)
            return self if self.__name__ == args[0].__name__ else args[0]
        return lambda func: self.__setitem__(args, func) or func

    def __get__(self, instance, owner):
        return self if instance is None else types.MethodType(self, instance)

    def parents(self, types: tuple) -> set:
        """Find immediate parents of potential key."""
        parents = {key for key in list(self) if isinstance(key, signature) and key < types}
        return parents - {ancestor for parent in parents for ancestor in parent.parents}

    def clean(self):
        """Empty the cache."""
        for key in list(self):
            if not isinstance(key, signature):
                super().__delitem__(key)

    def copy(self):
        """Return a new multimethod with the same methods."""
        return dict.__new__(type(self)).__ior__(self)

    def __setitem__(self, types: tuple, func: Callable):
        self.clean()
        if not isinstance(types, signature):
            types = signature(types)
        parents = types.parents = self.parents(types)
        with contextlib.suppress(ValueError):
            types.sig = inspect.signature(func)
        self.pop(types, None)  # ensure key is overwritten
        for key in self:
            if types < key and (not parents or parents & key.parents):
                key.parents -= parents
                key.parents.add(types)
        for index, cls in enumerate(types):
            if origins := set(subtype.origins(cls)):
                self.generics += [()] * (index + 1 - len(self.generics))
                self.generics[index] = tuple(origins.union(self.generics[index]))
        super().__setitem__(types, func)
        self.__doc__ = self.docstring

    def __delitem__(self, types: tuple):
        self.clean()
        super().__delitem__(types)
        for key in self:
            if types in key.parents:
                key.parents = self.parents(key)
        self.__doc__ = self.docstring

    def select(self, types: tuple, keys: set[signature]) -> Callable:
        keys = {key for key in keys if key.callable(*types)}
        funcs = {self[key] for key in keys}
        if len(funcs) > 1:
            groups = collections.defaultdict(set)
            for key in keys:
                groups[types - key].add(key)
            keys = groups[min(groups)]
            funcs = {self[key] for key in keys}
            if len(funcs) == 1:
                warnings.warn("positional distance tie-breaking is deprecated", DeprecationWarning)
        if len(funcs) == 1:
            return funcs.pop()
        raise DispatchError(f"{self.__name__}: {len(keys)} methods found", types, keys)

    def __missing__(self, types: tuple) -> Callable:
        """Find and cache the next applicable method of given types."""
        self.evaluate()
        types = tuple(map(subtype, types))
        if types in self:
            return self[types]
        return self.setdefault(types, self.select(types, self.parents(types)))

    def dispatch(self, *args) -> Callable:
        types = tuple(map(type, args))
        if not any(map(issubclass, types, self.generics)):
            return self[types]
        matches = {key for key in list(self) if isinstance(key, signature) and key.instances(*args)}
        matches -= {ancestor for match in matches for ancestor in match.parents}
        return self.select(types, matches)

    def __call__(self, *args, **kwargs):
        """Resolve and dispatch to best method."""
        self.evaluate()
        func = self.dispatch(*args)
        try:
            return func(*args, **kwargs)
        except TypeError as ex:
            raise DispatchError(f"Function {func.__code__}") from ex

    def evaluate(self):
        """Evaluate any pending forward references."""
        while self.pending:
            func = self.pending.pop()
            self[signature.from_hints(func)] = func

    @property
    def docstring(self):
        """a descriptive docstring of all registered functions"""
        docs = []
        for key, func in self.items():
            sig = getattr(key, 'sig', '')
            if func.__doc__:
                docs.append(f'{func.__name__}{sig}\n    {func.__doc__}')
        return '\n\n'.join(docs)

docstring property

a descriptive docstring of all registered functions

__call__(*args, **kwargs)

Resolve and dispatch to best method.

Source code in multimethod/__init__.py
364
365
366
367
368
369
370
371
def __call__(self, *args, **kwargs):
    """Resolve and dispatch to best method."""
    self.evaluate()
    func = self.dispatch(*args)
    try:
        return func(*args, **kwargs)
    except TypeError as ex:
        raise DispatchError(f"Function {func.__code__}") from ex

__missing__(types)

Find and cache the next applicable method of given types.

Source code in multimethod/__init__.py
348
349
350
351
352
353
354
def __missing__(self, types: tuple) -> Callable:
    """Find and cache the next applicable method of given types."""
    self.evaluate()
    types = tuple(map(subtype, types))
    if types in self:
        return self[types]
    return self.setdefault(types, self.select(types, self.parents(types)))

clean()

Empty the cache.

Source code in multimethod/__init__.py
296
297
298
299
300
def clean(self):
    """Empty the cache."""
    for key in list(self):
        if not isinstance(key, signature):
            super().__delitem__(key)

copy()

Return a new multimethod with the same methods.

Source code in multimethod/__init__.py
302
303
304
def copy(self):
    """Return a new multimethod with the same methods."""
    return dict.__new__(type(self)).__ior__(self)

evaluate()

Evaluate any pending forward references.

Source code in multimethod/__init__.py
373
374
375
376
377
def evaluate(self):
    """Evaluate any pending forward references."""
    while self.pending:
        func = self.pending.pop()
        self[signature.from_hints(func)] = func

parents(types)

Find immediate parents of potential key.

Source code in multimethod/__init__.py
291
292
293
294
def parents(self, types: tuple) -> set:
    """Find immediate parents of potential key."""
    parents = {key for key in list(self) if isinstance(key, signature) and key < types}
    return parents - {ancestor for parent in parents for ancestor in parent.parents}

register(*args)

Decorator for registering a function.

Optionally call with types to return a decorator for unannotated functions.

Source code in multimethod/__init__.py
278
279
280
281
282
283
284
285
286
def register(self, *args) -> Callable:
    """Decorator for registering a function.

    Optionally call with types to return a decorator for unannotated functions.
    """
    if len(args) == 1 and hasattr(args[0], '__annotations__'):
        multimethod.__init__(self, *args)
        return self if self.__name__ == args[0].__name__ else args[0]
    return lambda func: self.__setitem__(args, func) or func

multimethod.multidispatch

Bases: multimethod, dict[tuple[type, ...], Callable[..., RETURN]]

Wrapper for compatibility with functools.singledispatch.

Only uses the register method instead of namespace lookup. Allows dispatching on keyword arguments based on the first function signature.

Source code in multimethod/__init__.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class multidispatch(multimethod, dict[tuple[type, ...], Callable[..., RETURN]]):
    """Wrapper for compatibility with `functools.singledispatch`.

    Only uses the [register][multimethod.multimethod.register] method instead of namespace lookup.
    Allows dispatching on keyword arguments based on the first function signature.
    """

    signature: Optional[inspect.Signature]

    def __new__(cls, func: Callable[..., RETURN]) -> "multidispatch[RETURN]":
        return functools.update_wrapper(dict.__new__(cls), func)

    def __init__(self, func: Callable[..., RETURN]) -> None:
        self.pending = set()
        self.generics = []
        try:
            self.signature = inspect.signature(func)
        except ValueError:
            self.signature = None
        msg = "base implementation will eventually ignore annotations as `singledispatch does`"
        with contextlib.suppress(NameError, AttributeError, TypeError):
            hints = signature.from_hints(func)
            if hints and all(map(issubclass, hints, hints)):
                warnings.warn(msg, DeprecationWarning)
        super().__init__(func)

    def __get__(self, instance, owner) -> Callable[..., RETURN]:
        return self if instance is None else types.MethodType(self, instance)  # type: ignore

    def __call__(self, *args: Any, **kwargs: Any) -> RETURN:
        """Resolve and dispatch to best method."""
        params = self.signature.bind(*args, **kwargs).args if (kwargs and self.signature) else args
        func = self.dispatch(*params)
        return func(*args, **kwargs)

__call__(*args, **kwargs)

Resolve and dispatch to best method.

Source code in multimethod/__init__.py
422
423
424
425
426
def __call__(self, *args: Any, **kwargs: Any) -> RETURN:
    """Resolve and dispatch to best method."""
    params = self.signature.bind(*args, **kwargs).args if (kwargs and self.signature) else args
    func = self.dispatch(*params)
    return func(*args, **kwargs)

multimethod.subtype

Bases: ABCMeta

A normalized generic type which checks subscripts.

Transforms a generic alias into a concrete type which supports issubclass and isinstance. If the type ends up being equivalent to a builtin, the builtin is returned.

Source code in multimethod/__init__.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
class subtype(abc.ABCMeta):
    """A normalized generic type which checks subscripts.

    Transforms a generic alias into a concrete type which supports `issubclass` and `isinstance`.
    If the type ends up being equivalent to a builtin, the builtin is returned.
    """

    __origin__: type
    __args__: tuple

    def __new__(cls, tp, *args):
        if tp is Any:
            return object
        if hasattr(tp, '__supertype__'):  # isinstance(..., NewType) only supported >=3.10
            tp = tp.__supertype__
        if isinstance(tp, TypeVar):
            if not tp.__constraints__:
                return object
            tp = Union[tp.__constraints__]
        origin = get_origin(tp) or tp
        if hasattr(types, 'UnionType') and isinstance(tp, types.UnionType):
            origin = Union  # `|` syntax added in 3.10
        args = tuple(map(cls, get_args(tp) or args))
        if set(args) <= {object} and not (origin is tuple and args):
            return origin
        bases = (origin,) if type(origin) in (type, abc.ABCMeta) else ()
        if origin is Literal:
            bases = (subtype(Union[tuple(map(type, args))]),)
        if origin is Union:
            counts = collections.Counter()
            for arg in args:
                counts.update(cls for cls in get_mro(arg) if issubclass(abc.ABCMeta, type(cls)))
            bases = tuple(cls for cls in counts if counts[cls] == len(args))[:1]
        if origin is Callable and args[:1] == (...,):
            args = args[1:]
        namespace = {'__origin__': origin, '__args__': args}
        return type.__new__(cls, str(tp), bases, namespace)

    def __init__(self, tp, *args): ...

    def key(self) -> tuple:
        return self.__origin__, *self.__args__

    def __eq__(self, other) -> bool:
        return hasattr(other, '__origin__') and self.key() == subtype.key(other)

    def __hash__(self) -> int:
        return hash(self.key())

    def __subclasscheck__(self, subclass):
        origin = get_origin(subclass) or subclass
        args = get_args(subclass)
        if origin is Literal:
            return all(isinstance(arg, self) for arg in args)
        if origin is Union:
            return all(issubclass(cls, self) for cls in args)
        if self.__origin__ is Literal:
            return False
        if self.__origin__ is Union:
            return issubclass(subclass, self.__args__)
        if self.__origin__ is Callable:
            return (
                origin is Callable
                and signature(self.__args__[-1:]) <= signature(args[-1:])  # covariant return
                and signature(args[:-1]) <= signature(self.__args__[:-1])  # contravariant args
            )
        return (  # check args first to avoid recursion error: python/cpython#73407
            len(args) == len(self.__args__)
            and issubclass(origin, self.__origin__)
            and all(pair[0] is pair[1] or issubclass(*pair) for pair in zip(args, self.__args__))
        )

    def __instancecheck__(self, instance):
        if self.__origin__ is Literal:
            return any(type(arg) == type(instance) and arg == instance for arg in self.__args__)
        if self.__origin__ is Union:
            return isinstance(instance, self.__args__)
        if hasattr(instance, '__orig_class__'):  # user-defined generic type
            return issubclass(instance.__orig_class__, self)
        if self.__origin__ is type:  # a class argument is expected
            return inspect.isclass(instance) and issubclass(instance, self.__args__)
        if not isinstance(instance, self.__origin__) or isinstance(instance, Iterator):
            return False
        if self.__origin__ is Callable:
            return issubclass(subtype(Callable, *get_type_hints(instance).values()), self)
        if self.__origin__ is tuple and self.__args__[-1:] != (...,):
            if len(instance) != len(self.__args__):
                return False
        elif issubclass(self, Mapping):
            instance = next(iter(instance.items()), ())
        else:
            instance = itertools.islice(instance, 1)
        return all(map(isinstance, instance, self.__args__))

    @functools.singledispatch
    def origins(self) -> Iterable[type]:
        """Return origin types which would require instance checks.

        Provisional custom usage: `subtype.origins.register(<metaclass>, lambda cls: ...)
        """
        origin = get_origin(self)
        if origin is Literal:
            yield from set(map(type, self.__args__))
        elif origin is Union:
            for arg in self.__args__:
                yield from subtype.origins(arg)
        elif origin is not None:
            yield origin

origins()

Return origin types which would require instance checks.

Provisional custom usage: `subtype.origins.register(, lambda cls: ...)

Source code in multimethod/__init__.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
@functools.singledispatch
def origins(self) -> Iterable[type]:
    """Return origin types which would require instance checks.

    Provisional custom usage: `subtype.origins.register(<metaclass>, lambda cls: ...)
    """
    origin = get_origin(self)
    if origin is Literal:
        yield from set(map(type, self.__args__))
    elif origin is Union:
        for arg in self.__args__:
            yield from subtype.origins(arg)
    elif origin is not None:
        yield origin

multimethod.parametric

Bases: ABCMeta

A type which further customizes issubclass and isinstance beyond the base type.

Parameters:

Name Type Description Default
base

base type

required
funcs

all predicate functions are checked against the instance

required
attrs

all attributes are checked for equality

required
Source code in multimethod/__init__.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
class parametric(abc.ABCMeta):
    """A type which further customizes `issubclass` and `isinstance` beyond the base type.

    Args:
        base: base type
        funcs: all predicate functions are checked against the instance
        attrs: all attributes are checked for equality
    """

    def __new__(cls, base: type, *funcs: Callable, **attrs):
        return super().__new__(cls, base.__name__, (base,), {'funcs': funcs, 'attrs': attrs})

    def __init__(self, *_, **__): ...

    def __subclasscheck__(self, subclass):
        missing = object()
        attrs = getattr(subclass, 'attrs', {})
        return (
            set(subclass.__bases__).issuperset(self.__bases__)  # python/cpython#73407
            and set(getattr(subclass, 'funcs', ())).issuperset(self.funcs)
            and all(attrs.get(name, missing) == self.attrs[name] for name in self.attrs)
        )

    def __instancecheck__(self, instance):
        missing = object()
        return (
            isinstance(instance, self.__bases__)
            and all(func(instance) for func in self.funcs)
            and all(getattr(instance, name, missing) == self.attrs[name] for name in self.attrs)
        )

    def __and__(self, other):
        (base,) = set(self.__bases__ + other.__bases__)
        return type(self)(base, *set(self.funcs + other.funcs), **(self.attrs | other.attrs))

multimethod.multimeta

Bases: type

Convert all callables in namespace to multimethods.

Source code in multimethod/__init__.py
488
489
490
491
492
493
494
495
496
497
498
class multimeta(type):
    """Convert all callables in namespace to multimethods."""

    class __prepare__(dict):
        def __init__(*args):
            pass

        def __setitem__(self, key, value):
            if callable(value):
                value = getattr(self.get(key), 'register', multimethod)(value)
            super().__setitem__(key, value)

multimethod.DispatchError

Bases: TypeError

Source code in multimethod/__init__.py
16
17
class DispatchError(TypeError):
    pass