Skip to content

type alias to union is invalid in runtime context #5354

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?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions