[Python] mypy: argument of method incompatible with supertype

Discussão em 'Python' iniciado por Stack, Novembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    Look at the example code (mypy_test.py):

    import typing

    class Base:
    def fun(self, a: str):
    pass

    SomeType = typing.NewType('SomeType', str)

    class Derived(Base):
    def fun(self, a: SomeType):
    pass


    now mypy complains:

    mypy mypy_test.py
    mypy_test.py:10: error: Argument 1 of "fun" incompatible with supertype "Base"


    In that case, how can I work with class hierarchy and be type safe?

    Software versions:

    mypy 0.650 Python 3.7.1

    What I tried:

    import typing

    class Base:
    def fun(self, a: typing.Type[str]):
    pass

    SomeType = typing.NewType('SomeType', str)

    class Derived(Base):
    def fun(self, a: SomeType):
    pass


    But it didn't help.

    One user commented: "Looks like you cannot narrow down accepted types in overridden method?"

    But in that case, if I use the broadest type possible (typing.Any) in a base class signature it shoudn't work either. But it does:

    import typing

    class Base:
    def fun(self, a: typing.Any):
    pass

    SomeType = typing.NewType('SomeType', str)

    class Derived(Base):
    def fun(self, a: SomeType):
    pass


    No complains from mypy with the code directly above.

    Continue reading...

Compartilhe esta Página