python / python/mypy

a nonlocal in class nested within a function causes the referenced var to disappear from the outer scope

Open
#16,952 1 comment 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

c.f.: #12730

When a class definition appears within a function, a nonlocal in the class body causes the referenced variable to disappear from the outer scope.

To Reproduce

Analyze: [mypy-play.net]

from __future__ import annotations
from typing import (
        Optional,
        )
from typing_extensions import (
        assert_type,
        )

def in_a_function() -> None:

    some_value: Optional[int] = None

    assert_type(some_value, Optional[int])

    class SomeClass:

        nonlocal some_value
        assert_type(some_value, Optional[int])
        some_value = 42

    assert_type(some_value, Optional[int])
            # mypy: Expression is of type "Any", not "Optional[int]"
            #       [assert-type]
            # mypy: Name "some_value" is not defined  [name-defined]
    assert some_value == 42
            # mypy: Name "some_value" is not defined  [name-defined]
            # works at runtime

    print("all is well")  # is printed

if __name__ == '__main__':
    in_a_function()

Expected Behavior

This code should produce no errors. (Analogous code, outside a def, is analyzed correctly.)

Actual Behavior

See: mypy's output, inline as comments.

Your Environment

  • Mypy version used: 1.8.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.8, 3.12

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 provided reproducer and compare its behavior with the analogous top-level class example linked in the issue. Trace how mypy handles a nonlocal declaration in a class nested inside a function, then add a regression test showing that the outer variable remains typed and usable after the class; done means the reproducer produces no errors.

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.