mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Mapping imported from one's own module

Open gimperiale opened this issue 7 years ago • 1 comments

In my project I wrote a module pycompat.py:

import sys
from collections import abc

if sys.version < '3.5.3':
    class _ABCDummyBrackets(type(abc.Mapping)):  # abc.ABCMeta
        def __getitem__(cls, name):
            return cls

    class Mapping(abc.Mapping, metaclass=_ABCDummyBrackets):
        pass

else:
    from typing import Mapping

Which I then use in the other modules, e.g. mymod.py:

from .pycompat import Mapping

class MyDict(Mapping[KT, VT]):
    ...  # omissis

mypy 0.700, running on Python 3.7, fails with:

mymod.py.py:3: error: "Mapping" expects no type arguments, but 2 given

Workaround:

import sys
from typing import Mapping
if sys.version < '3.5.3':
    from .pycompat import Mapping

gimperiale avatar Apr 10 '19 11:04 gimperiale

You should use this:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from typing import Mapping
else:
    class Mapping(metaclass=YourCustomMeta):
        ...

If the version of typing is so old that it doesn't even have TYPE_CHECKING, you can define a special constant MYPY = False that is treated as always true during type checking and use if MYPY: ... etc.

ilevkivskyi avatar Apr 10 '19 12:04 ilevkivskyi