Skip to content

Defaulted TypeVar cannot be set to Never? #20391

@alicederyn

Description

@alicederyn

Bug Report

I have a type variable with a default set. For some reason, this seems to be causing mypy to refuse to allow that variable to be Never in constructor calls, but it's not explicitly banned: it just seems to silently revert it to the default, causing weird errors.

To Reproduce

from typing import Generic, Never, TypeVar

T = TypeVar("T")
D = TypeVar("D", default=int)

class NoDefault(Generic[T]): pass
class WithDefault(Generic[D]): pass

str_no_default: NoDefault[str] = NoDefault()
str_with_default: WithDefault[str] = WithDefault()
never_no_default: NoDefault[Never] = NoDefault()
never_with_default: WithDefault[Never] = WithDefault()

explicit_with_default: WithDefault[Never] = WithDefault[Never]()

Playground

Expected Behavior

I believe the above code should pass type-checking with no errors, as Never is a legal parameterization?

Actual Behavior

main.py:12: error: Incompatible types in assignment (expression has type "WithDefault[int]", variable has type "WithDefault[Never]")  [assignment]
main.py:14: error: Incompatible types in assignment (expression has type "WithDefault[int]", variable has type "WithDefault[Never]")  [assignment]
Found 2 errors in 1 file (checked 1 source file)

Playing around, I can get all kinds of weird errors that seem to come down to mypy somehow reverting Never to the default bound in construction calls.

Your Environment

  • Mypy version used: 1.19.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-pep-696TypeVar defaults

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions