python / python/mypy

Weird error with callable accepting non-positional arguments

Open
#9,810 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When answering this question on StackOverflow, I found a weird issue with mypy, which does not happen with either pyre or pytype.

Furthermore, by changing the identity function below to only accept positional arguments the problem is fixed.

To Reproduce
Check the following code with mypy

import functools
from typing import Iterable, TypeVar, Callable

T1 = TypeVar('T1')
T2 = TypeVar('T2')

def chain(
        functions: Iterable[Callable[[T1], T1]]
    ) -> Callable[[T1], T1]:

    def compose(
            f: Callable[[T1], T1],
            g: Callable[[T1], T1]
        ) -> Callable[[T1], T1]:
        def h(x: T1) -> T1:
            return g(f(x))
        return h

    def identity(x: T1) -> T1:
        return x

    return functools.reduce(compose, functions, identity)

def add_one(x):
    return x + 1

def mul_two(x):
    return x * 2

assert chain([add_one, mul_two, mul_two, add_one])(7) == 33```

Expected Behavior

I expected no errors

Actual Behavior

src/test.py:23: error: Argument 1 to "reduce" has incompatible type "Callable[[Arg(Callable[[T1], T1], 'f'), Arg(Callable[[T1], T1], 'g')], Callable[[T1], T1]]"; expected "Callable[[Callable[[Arg(T1, 'x')], T1], Callable[[T1], T1]], Callable[[Arg(T1, 'x')], T1]]"

Your Environment

  • Mypy version used: mypy 0.790
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.8.6
  • Operating system and version: MacOs Catalina

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproducer in the issue and compare mypy's handling of functools.reduce when the identity callable accepts positional arguments versus non-positional arguments. Verify the fix by checking that the supplied example is accepted without errors while preserving the reported callable typing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.