python / python/mypy

(🐞) Call to function decorated with a `Callable` causes inner function to fail to infer type of variable

Open
#8,900 2 comments 1 reaction 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

from typing import Any, Callable, TypeVar, _T as T

def bar() -> None:
    def inner() -> None:
        it.encode()  # error: Cannot determine type of 'it'
    breaks()
    it = ""
    
deco: Callable[[T], T]

@deco
def breaks() -> None: ...

It appears that the order of the function declarations affects the result(:trollface:):

from typing import Any, Callable, TypeVar

T = TypeVar("T")

deco: Callable[[T], T]

@deco
def doesnt_break() -> None: ...

def bar() -> None:
    def inner() -> None:
        it.encode()  # no error
    doesnt_break()
    it = ""

I have determined that this only happens when the deco is a Callable, when it is a function there is no error:

from typing import Any, TypeVar, _T as T

def bar() -> None:
    def inner() -> None:
        it.encode()  # no error
    doesnt_break()
    it = ""
    
def deco(fn: T) -> T: ...

@deco
def doesnt_break() -> None: ...

playground

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 by running the two Python reproductions from the issue, or use the linked playground, and compare Callable-based decoration with the function-based decorator. Trace the type inference path for the nested inner function and decorator call; done means the first example infers it as str without regressing the examples that already pass.

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
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.