Skip to content

Arguments annotated with typevars cannot have defaults #19092

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
eltoder opened this issue May 15, 2025 · 0 comments
Closed

Arguments annotated with typevars cannot have defaults #19092

eltoder opened this issue May 15, 2025 · 0 comments
Labels
bug mypy got something wrong

Comments

@eltoder
Copy link

eltoder commented May 15, 2025

Bug Report

Adding a default value for a function argument that uses a TypeVar in its type results in an error. This can be worked-around using overloads, but it would be better if it just worked out of the box.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=d0bdf572dbd887f02855ac9c4a28f20f

from typing import TypeVar

class Base:
    pass

T = TypeVar('T')
# Also fails: T = TypeVar('T', bound=Base)

def foo1(obj: T = Base()) -> list[T]:
    return [obj]

def foo2(ty: type[T] = Base) -> list[T]:
    return [ty()]

Expected Behavior

This should type-check with no errors.

Actual Behavior

main.py:9: error: Incompatible default for argument "obj" (default has type "Base", argument has type "T")  [assignment]
main.py:12: error: Incompatible default for argument "ty" (default has type "type[Base]", argument has type "type[T]")  [assignment]

Your Environment

  • Mypy version used: 1.15.0
  • Python version used: 3.11
@eltoder eltoder added the bug mypy got something wrong label May 15, 2025
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

2 participants