python / python/mypy

[bug] Assigning a builtin to a Callable changes its type to '<nothing>'

Open
#7,522 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

$ python --version                                                                                                                                 
Python 3.7.2

$ mypy --version
mypy 0.730+dev.8782ae7f789ad5b8cab97d3c8419f9f98b6eb285

Assigning a builtin to a Callable on the same line as the type declaration works, but doing so on separate lines does not:

$ mypy --strict -c "from typing import Callable, Any; cast: Callable[[Any], Any] = str; cast(5)"
Success: no issues found in 1 source file
$ mypy --strict -c "from typing import Callable, Any; cast: Callable[[Any], Any]; cast = str; cast(5)"
<string>:1: error: <nothing> not callable
Found 1 error in 1 file (checked 1 source file)

This becomes a problem when trying to assign builtins conditionally. Assigning lambda x: str(x) is a workaround, but is rather a hack.

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 two minimal mypy --strict -c reproductions in the issue and compare how callable type inference handles same-line versus separate assignments. Trace the assignment and builtin handling in mypy, then verify that both examples, including conditional builtin assignment, type-check without reporting <nothing> not callable.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.