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

Warn on unnecessary use of global #492

Open
Zac-HD opened this issue Sep 17, 2024 · 2 comments
Open

Warn on unnecessary use of global #492

Zac-HD opened this issue Sep 17, 2024 · 2 comments

Comments

@Zac-HD
Copy link
Member

Zac-HD commented Sep 17, 2024

CONSTANT = 1

def fn(x):
    global CONSTANT  # <- unnecessary, unidiomatic, and a (small) performance hit
    return x + CONSTANT

The global statement is only required when assigning to a global variable; you can reference outer namespaces without it. I think it'd be nice to have a lint rule that pointed this out, to help newer Pythonistas understand how scoping works.

@JelleZijlstra
Copy link
Collaborator

I have seen this too and agree it would be good for linters to warn against this. Is it in scope for flake8-bugbear, though? The README says this linter is there to find likely bugs or design problems in your code, and unnecessary global statements aren't bugs, they just do nothing.

a (small) performance hit

There appears to be no runtime hit; your function compiles to the same bytecode with and without the global statement. I guess it makes the initial compilation slightly slower.

@Zac-HD
Copy link
Member Author

Zac-HD commented Sep 17, 2024

Hmm, fair enough. Maybe a new W rule in pycodestyle?

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