Skip to content

Arguments annotated with typevars cannot have defaults #19092

Closed as duplicate of#3737
@eltoder

Description

@eltoder

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

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