python / python/mypy

Unsound assignment of a method to a Callable

Open
#16,549 5 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

Assigning functions to a name that was defined as a Callable is unsound and results in TypeErrors when run in Python.

To Reproduce

Just typecheck the code below with --strict:

class B():
    a: Callable[['B', int], int]
    def b(self, i: int) -> int: return 1
    a = b

B().a(B(), 1)

results in no errors.

Expected Behavior

Python however raises a TypeError for the same code:

>>> B().a(B(), 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: b() takes 2 positional arguments but 3 were given

I feel like Mypy should probably somdisallow assigning functions in the class body to Callable

Your Environment

  • Mypy version used: 9e1f4df133e155f213cf3714bf796bb9e8698907 (> v1.5.1)
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10

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

No source file or test is named. First run the supplied example with mypy --strict and compare it with Python's TypeError; then trace how class-body assignments to Callable annotations are checked. Done means the unsound assignment is rejected and a regression test covers the example.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.