coady / multimethod

Multiple argument dispatching.
https://coady.github.io/multimethod
Other
277 stars 24 forks source link

multidispatch.signature is set to the last registered function #51

Closed JacobHayes closed 3 years ago

JacobHayes commented 3 years ago

This may be working as intended, but I was a bit surprised that multidispatch.signature was always set to the last registered function (rather than the original function defining the "spec"). This works ok for methods with consistent parameters, but breaks in weird (but understandable) ways with different parameters:

from typing import Any

from multimethod import multidispatch

@multidispatch
def add(a: Any, b: Any) -> Any:
    ...

print(add.signature)  # (a: Any, b: Any) -> Any

@add.register
def add_str(a: str, b: str) -> str:
    return a + b

print(add.signature)  # (a: str, b: str) -> str
print(add("a", "b"))  # ab
print(add(a="a", b="b"))  # ab

@add.register
def add_extra(a: str, b: str, c: str) -> str:
    return a + b + c

print(add.signature)  # (a: str, b: str, c: str) -> str
print(add("a", "b"))  # ab
try:
    # This should route to add_str
    print(add(a="a", b="b"))
except TypeError as e:
    print(e)  # missing a required argument: 'c'
print(add(a="a", b="b", c="c"))  # abc

@add.register
def add_str(a: str, b: str) -> str:
    return a + b

print(add.signature)  # (a: str, b: str) -> str
print(add("a", "b"))  # ab
print(add(a="a", b="b"))  # ab
try:
    # This should route to add_extra
    print(add(a="a", b="b", c="c"))
except TypeError as e:
    print(e)  # got an unexpected keyword argument 'c'

This is caused by the signature being set in multidispatch.__init__, but overload.register (via multimethod.register) calling __init__ for each registered item. Support for dispatching on dynamic kwargs would be nice, but short of that, maybe just a note in the documentation?

I actually encountered this when trying to add a few extra checks in multidispatch.register in a subclass, but noticed that the .signature (and other .__init__ properties I added) changed every time.

coady commented 3 years ago

No, that's a bug. I'll have a look, thanks.