Skip to content

MyPy doesn't take into account default parameters when restricting typevars #16386

Closed as not planned
@andrewjw

Description

@andrewjw

Bug Report

If you have a function that uses a TypeVar to fix the type of multiple parameters, and one of those has a default value that restricts the possible types, MyPy doesn't raise an error if a caller uses the default parameter but has an invalid type in the other.

To Reproduce

from typing import Any, Callable, List, TypeVar

T = TypeVar("T", bound=Any)

def default_map(x: int) -> int:
    return x

def sum_values(values: List[T], map_func: Callable[[T], int] = default_map) -> int:
    return sum([map_func(x) for x in values])

sum_values(["abc", "defg"], map_func=len)

sum_values(["abc", "defg"])

Playground: https://mypy-play.net/?mypy=latest&python=3.12&gist=6733a6d4078776cb4c54bfca985c3dc5

Expected Behavior

MyPy should report an error for the second call to sum_values as str is not a valid type for T when the default map restricts it to int.

Actual Behavior

No error reported by MyPy, but a runtime error in Python.

Traceback (most recent call last):
  File "/Users/a.wilkinson1/Downloads/mypy_map_func_error.py", line 13, in <module>
    sum_values(["abc", "defg"])
  File "/Users/a.wilkinson1/Downloads/mypy_map_func_error.py", line 9, in sum_values
    return sum([map_func(x) for x in values])
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Your Environment

  • Mypy version used: 1.6.1
  • Python version used: 3.11 and 3.12

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