Skip to content

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

Closed
@robjwells

Description

@robjwells

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions