Skip to content
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

Optional and union syntax give different output with subclass of generic class #9942

Closed
robjwells opened this issue Jan 22, 2021 · 3 comments
Labels
bug mypy got something wrong

Comments

@robjwells
Copy link

Bug Report

Using Optional and the new union syntax for the type argument to a class's generic superclass cause mypy to report different errors (none for Optional[T], two for T | None).

To Reproduce

The behaviour can be seen in this example, where A is the generic superclass, B uses Optional, and C uses the new type union syntax.

from __future__ import annotations
from typing import Generic, Optional, TypeVar

T = TypeVar("T")

class A(Generic[T]):
    ...

class B(A[Optional[int]]):
    ...

class C(A[int | None]):
    ...

Expected Behavior

My expectation is that and Optional[T] and T | None are equivalent.

Actual Behavior

mypy reports the following for only the class using the union syntax:

$ mypy repro.py
repro.py:12: error: Type expected within [...]
    class C(A[int | None]):
            ^
repro.py:12: error: Invalid base class "A"
    class C(A[int | None]):
            ^
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.800
  • Mypy command-line flags: Occurs with --strict and without.
  • Python version used: 3.9.0
@robjwells robjwells added the bug mypy got something wrong label Jan 22, 2021
@JelleZijlstra
Copy link
Member

I believe this syntax is invalid at runtime in 3.9 (it will work in 3.10). Does it work if you run the file?

@robjwells
Copy link
Author

Ah, no, it doesn't:

Traceback (most recent call last):
  File "/Users/robjwells/Dropbox/projects/adventofcode-solutions/2016/python/repro.py", line 12, in <module>
    class C(A[int | None]):
TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'

@hauntsaninja
Copy link
Collaborator

hauntsaninja commented Jan 22, 2021

Yeah, the PEP 604 support in mypy doesn't work well for runtime use cases yet (i.e. things that will only work on 3.10). Closing as a dupe of #9880

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