Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

If a with statement’s target is a global variable that was assigned before, a false “redefinition of unused variable” is reported. #14257

Open
manueljacob opened this issue Nov 11, 2024 · 1 comment

Comments

@manueljacob
Copy link
Contributor

from contextlib import nullcontext

def f():
    global glob
    glob = 0
    assert g() == 0
    with nullcontext(enter_result=1) as glob:
        assert g() == 1

def g():
    return glob

With ruff 0.7.3:

test.py:8:41: F811 Redefinition of unused `glob` from line 6
  |
6 |     glob = 0
7 |     assert g() == 0
8 |     with nullcontext(enter_result=1) as glob:
  |                                         ^^^^ F811
9 |         assert g() == 1
  |
  = help: Remove definition: `glob`

Found 1 error.

However, glob is used by g(), so neither of the assignments can be removed.

I’m aware that according to the Python documentation, “names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation”. However, that is currently not enforced by CPython or PyPy. There could be a ruff rule that reports an error in this case, but that’s a separate issue.

@MichaReiser
Copy link
Member

@AlexWaygood would you mind taking a look at this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants