python / python/mypy

Decorator becomes untyped when it accepts an object of the same type as a certain global.

Open
#14,005 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

A decorator becomes untyped when it accepts an argument for which we have another instance, globally defined and referred to in the same scope.

The comments in the example should make the bug much more clear.
I had no idea how to describe this issue or search for it, so no idea whether it was reported before.

To Reproduce

from typing import Callable


class Something:
    pass


def decorator(buffer: Something) -> Callable[[Callable[[], None]], Callable[[], None]]:
    return lambda x: x


def main() -> None:
    something  # Comment out this line and everything is fine.
    another_something = Something()

    @decorator(another_something)
    def func() -> None:
        return


something = Something()  # Move this above `main` and everything is fine.

Expected Behavior

The code snippet should pass.

Actual Behavior

 $ mypy --strict /tmp/test.py
test.py:16: error: Untyped decorator makes function "func" untyped
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.982
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.9.13

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 reproducing the snippet with mypy --strict and compare behavior when the global something is removed or moved above main. Trace the decorator type inference and name-resolution path involved in this example. Done means the original snippet passes strict checking without reporting an untyped decorator.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.