coady / multimethod

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

overloading private methods #124

Closed Wouter1 closed 2 months ago

Wouter1 commented 2 months ago

Describe the bug If the method being overloaded (with @multimethod) is a private method, calling the method seems to fail

To Reproduce

$ pip list
Package       Version
------------- -------
multimethod   1.10   
pip           20.0.2 
pkg-resources 0.0.0  
setuptools    44.0.0 

Now in python commandline do

from __future__ import annotations
from multimethod import multimethod
from typing import TypeVar, Type, Optional

class A:
 @multimethod
 def __f(self, x:Optional[int])->int:
  return 1
 @multimethod
 def __f(self, x:int, y:int)->int:
  return 2
 def test(self):
   return self.__f(1)

Now call A().test()

Expected behavior prints 1

Actual behavior

>>> A().test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in test
  File "/home/wouter/venv/lib/python3.8/site-packages/multimethod/__init__.py", line 326, in __call__
    func = self[tuple(func(arg) for func, arg in zip(self.type_checkers, args))]
  File "/home/wouter/venv/lib/python3.8/site-packages/multimethod/__init__.py", line 320, in __missing__
    raise DispatchError(msg, types, keys)
multimethod.DispatchError: ('__f: 0 methods found', (<class '__main__.A'>, <class 'int'>), [])

My first guess is that the method resolver does not realize that __f results in a mangled name.

coady commented 2 months ago

My first guess is that the method resolver does not realize that __f results in a mangled name.

Yes, the register method can be used explicitly instead of the "magic" namespace lookup.

class A:
 @multimethod
 def __f(self, x:Optional[int])->int:
  return 1
 @__f.register
 def _(self, x:int, y:int)->int:
  return 2
Wouter1 commented 2 months ago

@coady thanks for the quick response and confirmation of the issue. Also thanks for the workaround.

However I believe this case should be handled automatically.