[Python] What's the best practice of typing hint after python 3.9?

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    After python3.9, there are at least three ways to use typing hint. Take the build-in collection set for instance:

    # way 1
    def f(s: set[str]) -> str:
    pass

    # way 2
    def f(s: typing.Set[str]) -> str:
    pass

    # way 3
    def f(s: collections.abc.Set[str]) -> str:
    pass

    # way 3': or arguable collections.abc.MutableSet vs collections.abc.Set
    def f(s: collections.abc.MutableSet[str]) -> str:
    pass


    Furthermore, for some abstract type there are two version in typing and collections.abc, take Mapping for instance:

    def f(m: typing.Mapping[str, int]) -> int:
    pass

    def f(m: collections.abc.Mapping[str, int]) -> int:
    pass


    According to The Zen of Python:


    There should be one-- and preferably only one --obvious way to do it.
    ​

    I am confused which one is best?

    Continue reading...

Compartilhe esta Página