Skip to content

TypeAlias does not work with Union types #11665

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
realharry opened this issue Dec 5, 2021 · 4 comments
Closed

TypeAlias does not work with Union types #11665

realharry opened this issue Dec 5, 2021 · 4 comments
Labels
bug mypy got something wrong

Comments

@realharry
Copy link

Bug Report

Union types are valid types, just like any other types. That's at least my expectation. However, you cannot currently type alias union types.

For example,

X: TypeAlias = int | str  #   line 3

def f(b: bool) -> X:     # line 6
    if b:
        return 3
    else:
        return "three"

Mypy will issue the following errors:

typealias_test.py:3: error: Variable "typing.TypeAlias" is not valid as a type
typealias_test.py:6: error: Variable "typealias_test.X" is not valid as a type

To Reproduce

  1. Create a type alias for a union type, using either typing.Union or the 3.10 vert bar syntax.
  2. You can explicitly declare the type alias implicitly or explicitly with typing.TypeAlias.
  3. Run mypy check. Union type aliases are not recognized as type by mypy.

Expected Behavior

Union types should be treated as just any other types.

Actual Behavior

Union types cannot be type-aliased in the current impl of mypy.

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10.0
  • Operating system and version: Ubuntu 20.04.
@realharry realharry added the bug mypy got something wrong label Dec 5, 2021
@realharry
Copy link
Author

realharry commented Dec 5, 2021

It seems slightly more complicated than I initially thought. Type alias X = Union[T1, T2] works. However, X: TypeAlias = Union[T1, T2] does not work. For the 3.10 syntax, neither X = T1 | T2 nor X: TypeAlias = T1 | T2 work.

@hauntsaninja
Copy link
Collaborator

hauntsaninja commented Dec 5, 2021

All variants you've described should work on master

@jborman-exos
Copy link

I have the same specs as @realharry and am experiencing the same issue. Using an explicit Union[T1, T2] works however the union operator | does not.

@hauntsaninja
Copy link
Collaborator

These work with newer mypy (e.g. 0.931).
There's still some issues with generic type aliases ( #12211 ), but most type aliases are not generic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants