Can I Use __qualname__ In A Python Type Hint With Postponed Annotation Evaluation?
I like using __qualname__ for the return-type annotation of factory-style class methods, because it doesn't hardcode the classname and therefore keeps working subclasses (cf. this
Solution 1:
Foo.make
doesn't always return an instance of Foo
(which is what __qualname__
expands to). It returns an instance of the class it receives as an argument, which isn't necessarily Foo
. Consider:
>>>classFoo:... @classmethod...defmake(cls):...return cls()...>>>classBar(Foo):...pass...>>>type(Bar.make())
<class '__main__.Bar'>
The correct type hint would be a type variable:
T = TypeVar("T", bound="Foo")
classFoo:@classmethoddefmake(cls: Type[T]) -> T:return cls()
Post a Comment for "Can I Use __qualname__ In A Python Type Hint With Postponed Annotation Evaluation?"