Equivalent to super () for functools.singledispatch

functools.singledispatch helps define a one-time generic method. Meanwhile, there is super() for calling methods or accessing superclass attributes.

Is there something like super() that can be used with singledispatch ? I tried the following, but the result of super(Derived, value) is just not an instance of Base , so it does not work as I expected:

 from functools import singledispatch @singledispatch def hello(value): return ['default'] @hello.register(Base) def hello_base(value): return hello(super(Base, value)) + ['base'] @hello.register(Derived) def hello_derived(value): return hello(super(Derived, value)) + ['derived'] print(hello(Derived()) # expected ['default', 'base', 'derived'], # but actually is ['default', 'derived']. 
+6
source share
1 answer

I believe something like this will work, but I cannot test it, since I do not have Python 3.4 installed:

 def getsuperclass(cls): try: nextclass = cls.__mro__[1] except IndexError: raise TypeError("No superclass") return nextclass @singledispatch def hello(value): return ['default'] @hello.register(Base) def hello_base(value): return hello.dispatch(getsuperclass(Base))(value) + ['base'] @hello.register(Derived) def hello_derived(value): return hello.dispatch(getsuperclass(Derived))(value) + ['derived'] print(hello(Derived())) 

Note that it doesn’t actually make sense to call hello with the superclass as an argument, because if you did, you would lose the original argument ( value ) that was passed. In your case, it does not matter because your function does not use value at all, but the actual dispatch function will probably really do something with the value, so you need to pass the value as an argument.

+2
source

Source: https://habr.com/ru/post/974529/


All Articles