Skip to content

type alias to union is invalid in runtime context #5354

Closed
@glyph

Description

@glyph

As of MyPy 0.620:

# aliases.py
from typing import Union
x = Union[int, str]
def y() -> None:
    print(x)

This produces the error:

aliases.py:5: error: The type alias to Union is invalid in runtime context

However, type variables are quite useful in "runtime context" in order to implement things like serialization; for example, https://github.com/Tinche/cattrs makes heavy use of introspecting Union objects to determine which types are valid.

Those of us hacking around code like this have known that the current API for enumerating the members of a Union was private & internal, and not for public consumption, so we've been keeping pace with implementation details while waiting for a public API to get this information to emerge. These errors are super annoying because they imply the only future-looking direction for this type of code will involve manually re-typing the same list of types for every union alias defined anywhere.

Can this change be backed out? If not, is there any guidance for how to define a Union such that it is introspectable?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions