Subclass in type hinting

Subclass in type hinting



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?


(cls: A)






Is Python also raising this error ? Otherwise, it's maybe a bug in PyCharm !

– jpic
Sep 7 '17 at 9:05






For me I tried on python console and It is working fine. Might be possible bug in PyCharm..

– Nirmi
Sep 7 '17 at 9:13






Yes it's working, the type hinting is optional as far as I know. Still I want the user of the method to explicitly know what classes are intended for usage there.

– user1211030
Sep 7 '17 at 9:14





2 Answers
2



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.


cls: A


cls


A


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] where C is a class. In
other words, when C is the name of a class, using C to annotate an
argument declares that the argument is an instance of C (or of a
subclass of C), but using Type[C] as an argument annotation declares
that the argument is a class object deriving from C (or C itself).


Type[C]


C


C


C


C


C


Type[C]


C


C



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.



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế