I have the following classes setup:
class A:
pass
class B(A):
pass
class C(A):
pass
Then I have a method that gets called with 2 arguments:
- x -> always a string
- y -> one of the classes above (A, B, or C) And we do something different depending on which class was passed as second argument.
@multimethod
def click(x: str, y: A=None):
do_A_thing()
@multimethod
def click(x: str, y: B=None):
do_B_thing()
@multimethod
def click(x: str, y: object=None):
raise expeption
With this configuration, an exception is always raised even when y is of type A or B.
I also looked at using singledispatch, but I need the validation on the second argument and I can't switch their places. I also tried using multipledispatch, but it didn't work similarly to multimethod.
Have a look to the
doc
. Notice further that the dispatch occurs "on the type of the first argument". So you should refactor the signature of the functions.Here a minimal working example for a functions annotated with types
and for a function which doesn’t use type annotations you need to pass the appropriate type argument explicitly to the decorator itself
For switching the order of the argument it's enough to define a decorator,
arg_swapper
, with this functionalityNotice that you either stack the decorators (as shown above) or do an explicit call