[Python] What is the convention for type annotating trivial lines of code that instantiate a...

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    As I'm unable to find a better way to phrase the question, I'm not able to find any reasonable discussions on the topic.

    Consider the following:

    import queue
    my_queue: queue.Queue = queue.Queue()


    I have been annotating code as shown above for a long time. However, each time I do so, I feel strange. Consider the alternative:

    import queue
    my_queue = queue.Queue()


    The latter seems to be superior in terms of readability (at least for me). However, afraid that some tool or the other may be unable to discern the appropriate type for my_queue, I have always written the former.

    This can especially be a problem when the type in question is very long (and the code starts to look more akin to Java rather than Python). I am aware of the fact that aliasing a type is possible. Regardless, I feel that the latter is more readable for humans.

    Has this topic perhaps been addressed in a PEP? Do any tools (for documentation, linting, analysis, etc.) behave differently in either case?

    Continue reading...

Compartilhe esta Página