python / python/mypy

deleting a class-scoped variable that shadows a global variable causes mypy to think it's undefined

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

Nobody has claimed this yet.

bug topic-runtime-semantics topic-variable-scope
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

To Reproduce

from typing import Callable, TypeVar

T = TypeVar("T")

x = 1


def decorate(num: int) -> Callable[[T], T]:
    def thru(it: T) -> T:
        print("decorating", it, "with", num)
        return it
    return thru


class y(object):
    @decorate(x)
    def a(self) -> None:
        ...

    x = 2

    @decorate(x)
    def b(self) -> None:
        ...

    del x

    @decorate(x)
    def c(self) -> None:
        ...

Expected Behavior

This is perfectly valid, it should not cause an error! It works at runtime.

Actual Behavior

$ mypy class_scope.py 
class_scope.py:28: error: Trying to read deleted variable 'x'
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.790
  • Mypy command-line flags: all defaults
  • Mypy configuration options from mypy.ini (and other config files): no mypy.ini
  • Python version used: Python 3.8.5
  • Operating system and version:
ProductName:	Mac OS X
ProductVersion:	10.15.7
BuildVersion:	19H2

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

Reproduce the issue from the class_scope.py example with mypy, using the reported Python and mypy versions as a baseline. Trace how the checker handles a class-scoped name after del x, then add a regression test showing that the later decorator use does not report an undefined variable.

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
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.