Skip to content

Instantly share code, notes, and snippets.

@ales-erjavec
Created October 29, 2021 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ales-erjavec/d35800a539411b2e2c571ee056f570f1 to your computer and use it in GitHub Desktop.
Save ales-erjavec/d35800a539411b2e2c571ee056f570f1 to your computer and use it in GitHub Desktop.
from functools import singledispatch
def singledispatch_next(f):
"""
Decorate a `singledispatch` function f with a `next` method.
`f.next(__class__)` dispatches to the 'base' or next implementation in
the __class__'s mro chain.
Example
-------
>>> @singledispatch_next
... @singledispatch
... def func(a):
... print("In default func impl.")
...
>>> @func.register(int)
... def func_int(a):
... print("In func_int.")
... func.next(int)(a)
...
>>> func(1)
In func_int.
In default func impl.
"""
def next_(cls):
mro = cls.mro()
if len(mro) > 1:
return f.dispatch(mro[1])
else:
raise TypeError(f"{cls} has no next")
f.next = next_
return f
@singledispatch_next
@singledispatch
def f(a):
print("Im", a)
@f.register(int)
def fi(a):
print("Im a int", a)
@f.register(bool)
def fb(a):
f.next(bool)(a)
print("Im an int too", a)
f("")
f(1)
f(True)
print(f.dispatch(bool.mro()[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment