Created
October 29, 2021 12:16
-
-
Save ales-erjavec/d35800a539411b2e2c571ee056f570f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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