coady / multimethod

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

Multimethod on __init__ fails mypy #38

Closed marcus7070 closed 3 years ago

marcus7070 commented 3 years ago

With a test.py containing:

from multimethod import multimethod

class Test:

    @multimethod
    def __init__(self) -> None:
        pass

    @__init__.register
    def _(self, a: int) -> None:
        pass
> mypy test.py
test.py:6: error: Unsupported decorated constructor type
Found 1 error in 1 file (checked 1 source file)

Can I multimethod an __init__ (and pass mypy)? Sorry if I'm missing anything obvious, I'm just getting started with multiple dispatch.

coady commented 3 years ago

To override mypy, you can do this:

@multimethod  # type: ignore
marcus7070 commented 3 years ago

Thanks.

I've also realised that applying multimethod to __init__ sets the resulting object's type to Any.

from multimethod import multimethod

class Test:

    @multimethod  # type: ignore[misc]
    def __init__(self) -> None:
        pass

    @__init__.register
    def _int(self, a: int) -> None:
        self.i = a

    @__init__.register
    def _str(self, a: str) -> None:
        self.s = a

class Vanilla:

    def __init__(self) -> None:
        pass

t0 = Test(1)
reveal_type(t0)

t1 = Vanilla()
reveal_type(t1)
> mypy test.py
test.py:26: note: Revealed type is 'Any'
test.py:29: note: Revealed type is 'test.Vanilla'

Is there any way to get type inference working with multimethod __init__?