from abc import ABC, abstractmethod
from typing import Dict, Generic, List, TypeVar
T = TypeVar("T")
class FooGenericAbstract(ABC, Generic[T]):
@abstractmethod
def func(self) -> T:
pass
class Foo(FooGenericAbstract[Dict[str, int]]):
def func(self) -> Dict[str, str]:
pass
With coc.nvim and python 3.8, mypy 0.770 warns as expected.
I guess maybe you should use type hints instead of built-in types, since mypy cannot recognize the built-in types until now.
Answer from ssfdust on Stack Overflowfrom abc import ABC, abstractmethod
from typing import Dict, Generic, List, TypeVar
T = TypeVar("T")
class FooGenericAbstract(ABC, Generic[T]):
@abstractmethod
def func(self) -> T:
pass
class Foo(FooGenericAbstract[Dict[str, int]]):
def func(self) -> Dict[str, str]:
pass
With coc.nvim and python 3.8, mypy 0.770 warns as expected.
I guess maybe you should use type hints instead of built-in types, since mypy cannot recognize the built-in types until now.
PyCharm has very weak support for type hints in general, so always be advised to rely on the Mypy plugin available in the JetBrains marketplace.
Your example is one of those cases where explicit annotations silently override the types specified by the base class, even when using the uppercase List and Dict types from the typing module. It raises an error as expected using the Mypy plugin.
Inheriting Generic and ABC: Which order?
python - User defined generic types and collections.abc - Stack Overflow
Variance of arguments for Generic ABC vs Generic Protocol
abstractmethod + generic method seems to disturb inference results
Your original code works fine with the current version of python and mypy, and does everything exactly as you want (including reusing implementation from collections.abc.Mapping).
However, for the time being, you should remove the bound=Hashable, since it's not fully supported yet:
from typing import TypeVar, Hashable, Mapping
K = TypeVar("K")
V = TypeVar("V")
class MyMapping(Mapping[K, V]):
...
Now that typing.Mapping is deprecated and its functionalities are "transferred" to collections.abc.Mapping, this will work without a hitch:
from collections.abc import Mapping, Hashable
from typing import TypeVar
K = TypeVar('K', bound = Hashable)
V = TypeVar('V')
class MyMapping(Mapping[K, V]):
...
This has been possible ever since Python 3.9 via PEP 585.
Or, if you prefer PEP 695/Python 3.12+ syntax:
from collections.abc import Mapping, Hashable
class MyMappingK: Hashable, V:
...