Skip to content

Callable not deduced correctly #16868

@nschloe

Description

@nschloe

I have a function add(x,y) that adds two floats, and that that the user can specify. If no custom function add is given, default_add is used. If it is given, I'm adding a little wrapper code to assert stuff:

from typing import Callable


def default_add(x: float, y: float, extra: float = 0) -> float:
    return x + y + extra


def wrap_add(
    add: Callable[[float, float], float],
) -> Callable[[float, float], float]:
    def _add(x: float, y: float) -> float:
        assert isinstance(x, (float, int))
        assert isinstance(y, (float, int))

        z = add(x, y)

        assert isinstance(z, (float, int))
        return z

    return _add


fun: Callable[[float, float], float] | None = None

fun2 = default_add if fun is None else wrap_add(fun)

fun2(3, 5)

Running mypy on the above gives

a.py:27: error: Cannot call function of unknown type  [operator]

When adding explicit typing to fun2,

fun2: Callable[[float, float], float] = default_add if fun is None else wrap_add(fun)

one incorrectly gets

a.py:25: error: Incompatible types in assignment (expression has type "function", variable has type "Callable[[float, float], float]") 

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-join-v-unionUsing join vs. using unions

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions