pythonmultimethod

Python multimeta with nested classes


I would expext the following example to work, but it does not. Am I missing something obvious or is there a reason why multimeta seemingly does not work with nested classes?

[N.B. As a workaround i am using the @multimethod decorator on individual functions instead]

from __future__ import annotations

from multimethod import multimeta

class Foo(metaclass=multimeta):
 
  class _Bar(metaclass=multimeta):

    def __init__(self, parent: Foo) -> None:
      self._parent = parent

  def __init__(self) -> None:
    self._baz = self._Bar(self)


if __name__ == "__main__":
  foo = Foo()

Solution

  • Is this what you're looking for?

    from __future__ import annotations
    
    from multimethod import multimeta
    
    
    class Foo(metaclass=multimeta):
        class _Bar(metaclass=multimeta):
    
            def __init__(self, parent: Foo) -> None:
                self._parent = parent
    
        def __init__(self) -> None:
            self._baz = self.__class__._Bar(self)
    
    
    if __name__ == "__main__":
        foo = Foo()
    

    This compiles and runs without issues. The difference is the .__class__ reference in the __init__ for Foo.

    I haven't looked into the exact details, but it appears that multimethod.multimethod causes a dispatch error when you try to access the class attribute class directly, and instead tries to access it as an instance attribute class.