[Python] Subclass in type hinting

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    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 instead.


    How can I change type hinting here to accept any subtypes of A?

    According to PEP 484 ("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?

    Continue reading...

Compartilhe esta Página