I want to allow type hinting using Python 3 to accept sub classes of a certain class. E.g.:
class A:
pass
class B(A):
pass
class C(A):
pass
def process_any_subclass_type_of_A(cls: A):
if cls == B:
# do something
elif cls == C:
# do something else
Now when typing the following code:
process_any_subclass_type_of_A(B)
I get an PyCharm IDE hint 'Expected type A, got Type[B] instead.'
How can I change type hinting here to accept any subtypes of A?
According to this (https://www.python.org/dev/peps/pep-0484/#type-definition-syntax, "Expressions whose type is a subtype of a specific argument type are also accepted for that argument."), I understand that my solution (cls: A) should work?
When you do cls: A, you're saying that cls is going to an instance of type A. To make it work with type or its subtypes use typing.Type.
from typing import Type
def process_any_subclass_type_of_A(cls: Type[A]):
pass
From The type of class objects :
Sometimes you want to talk about class objects that inherit from a given class. This can be spelled as
Type[C]whereCis a class. In other words, whenCis the name of a class, usingCto annotate an argument declares that the argument is an instance ofC(or of a subclass ofC), but usingType[C]as an argument annotation declares that the argument is a class object deriving fromC(orCitself).
I found the soluton. Use:
from typing import Type
def process_any_subclass_type_of_A(cls: Type[A]):
pass
And the desired behavior will be there as noted in the PEP above.
来源:https://stackoverflow.com/questions/46092104/subclass-in-type-hinting