[Python] Explicitly stating the type of a loop variable [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    I'm quite new to Python (and its duck typing), but am currently working on a Python project that needs serious refactoring. In a for loop, I need to discriminate between items of a list based on their type, and call functions defined in the derived class. What is the Python way of doing this? Consider this:

    from typing import List

    class A:
    def __init__(self):
    pass

    class B(A):
    def my_function(self):
    print("I'm of type B.")

    collection: List[A] = [A(), B(), A(), B(), B()]

    # select only the B items and call their specific function
    for object in [item for item in collection if isinstance(item, B)]
    object.my_function() # <- no help from the IDE here


    In that last line, object is expected to be of type A. Since type hinting the loop variable is not allowed, I could introduce a more specific variable, because I already did the type checking:

    for object in [item for item in collection if isinstance(item, B)]
    b: B = object # a "sort-of" cast
    b.my_function() # <- IDE recognizes b to be of type B


    I'd like to only use the means provided by Python itself, not PyCharm or similar tools. Is there a better way of achieving type hinting support besides introducing a type-hinted extra variable?

    Continue reading...

Compartilhe esta Página