[Python] Create recursive TypeAlias at runtime [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 3, 2025.

  1. Stack

    Stack Membro Participativo

    For the use with pydantic, I want to create recursive type aliases at runtime. “Normal” type aliases are possible like this:

    from typing import TypeAliasType

    alias = TypeAliasType("alias", str)
    foo: alias = "bar"


    But now I want to create a recursive type alias like this one:

    from collections.abc import Sequence

    type recursive = int | Sequence[recursive]


    This includes a forward reference, which I found impossible to emulate at runtime. There is ForwardRef, but besides being discouraged it did not work for me:

    from typing import ForwardRef, TypeAliasType
    from collections.abc import Sequence

    type recursive = int | Sequence[recursive]
    print(recursive.__value__) # int | collections.abc.Sequence[recursive]

    ref = ForwardRef("recursive")
    recursive = TypeAliasType("recursive", int | Sequence[ref])
    print(recursive.__value__) # int | collections.abc.Sequence[ForwardRef('recursive')]


    How can I declare such a recursive type alias during runtime?

    More context: I have a pydantic model inside some package that offers support for plugins. This model has some fields like mylist: Sequence[MyTypeAlias], where MyTypeAlias describes a union of allowed types. The plugins are now supposed to expand this list of allowed types with their own models. The solution I am aiming for is to collect this list and replace all occurences of MyTypeAlias with the updated union. This works well, except for the recursive types mentioned here. Other options to manually mark all such occurences (which are many) would decrease readability in the models of the main package, so I chose this approach.

    Continue reading...

Compartilhe esta Página