Inherit generic type in python 3 with typing
This was a bug in mypy that was fixed in mypy 0.700. As several people in the comments noted, that line of code validates fine in newer versions.
Note that in newer versions of mypy, the code in the question has a different problem:
main.py:8: error: Incompatible types in assignment (expression has type "None", variable has type "EntityId")main.py:9: error: Incompatible types in assignment (expression has type "None", variable has type "StateType")
But that's outside the scope of the question and up to you to resolve however you'd like.
I know this question is a little old, but just for future reference:
from __future__ import annotationsfrom typing import NamedTuple, Optional, Typeclass UserState(NamedTuple): name: str age: intclass Entity: id: Optional[str] state: UserState @classmethod def from_state(cls: Type[Entity], state: UserState) -> Entity: entity_from_state: Entity = object.__new__(cls) entity_from_state.id = None entity_from_state.state = state return entity_from_state def assign_id(self, id: str) -> None: self.id = idclass User(Entity): def __init__(self, name: str, age: int) -> None: self.state = UserState(name=name, age=age) @property def name(self) -> str: return self.state.name @property def age(self) -> int: return self.state.age def have_birthday(self) -> None: new_age = self.state.age + 1 self.state = self.state._replace(age=new_age)# Create first object with constructoru1 = User(name="Anders", age=47)# Create second object from stateuser_state = UserState(name="Hannes", age=27)u2 = User.from_state(user_state) # Line 47print(u1.state)print(u2.state)