Typing on child class' methods of a Generic base class

Nicolas Haller python at boiteameuh.org
Wed Mar 9 10:53:18 EST 2022


Hello,

I am wondering about a situation involving typing, Generic and a child 
class.

The documentation about "user-defined generic types"[1] says that I can 
fix some types on a child class (class MyDict(Mapping[str, T]):) but 
doesn't say much about the signature of the methods I need to 
implement/override on that child class.

Should I keep the TypeVar and remember that I fixed the type(alternative 
1) or change the signature of the method to replace the TypeVar by the 
type I set (alternative 2)?

Mypy seems to prefer the second alternative but changing the signature 
feels wrong to me for some reason. That's why I'm asking :-)


Below is a small example to illustrate:
----
from abc import ABCMeta, abstractmethod
from typing import TypeVar, Generic


T = TypeVar("T")


class Base(Generic[T], metaclass=ABCMeta):
     """A base class."""

     @abstractmethod
     def _private_method(self, an_arg: T) -> T:
         ...

     def public_method(self, an_arg: T) -> T:
         from_private_method = self._private_method(an_arg)
         return from_private_method


class Alternative1(Base[int]):
     def _private_method(self, an_arg: T) -> T:  # I keep T
         return 42


class Alternative2(Base[int]):
     def _private_method(self, an_arg: int) -> int:  # I replace T
         return 42
----

Thanks,

-- 
Nicolas Haller


[1]: 
https://docs.python.org/3/library/typing.html#user-defined-generic-types


More information about the Python-list mailing list