python / python/mypy

New semanal: Spurious "no binding for nonlocal"

Open
#7,057 1 comment 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal semantic-analyzer topic-runtime-semantics topic-variable-scope
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

$ cat santa/scheduler/loop.py 
import signal
from typing import Any


def loop() -> None:
    def signal_handler(signum: Any, frame: Any) -> None:
        nonlocal running
        running = False

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    running = True
    while running:
        pass
$ mypy --new-semantic-analyzer santa/scheduler/loop.py 
santa/scheduler/loop.py:7: error: No binding for nonlocal 'running' found

This code passes under the old semantic analyzer. The error goes away if I move the running = True line above the definition of the nested function.

It doesn't seem unreasonable to me to require that the definition of a variable is lexically before its use as a nonlocal, so maybe this doesn't need to be fixed.

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 reproducer in santa/scheduler/loop.py and run mypy --new-semantic-analyzer on it, comparing the result with the old semantic analyzer. Determine whether a nonlocal binding introduced later in the enclosing function should be accepted; done means the behavior is settled and the reported diagnostic matches that decision.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.