flake8-bugbear icon indicating copy to clipboard operation
flake8-bugbear copied to clipboard

Warn on unnecessary use of `global`

Open Zac-HD opened this issue 1 year ago • 3 comments

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.

Zac-HD avatar Sep 17 '24 19:09 Zac-HD

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.

JelleZijlstra avatar Sep 17 '24 19:09 JelleZijlstra

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

Zac-HD avatar Sep 17 '24 21:09 Zac-HD

What about a warning for the opposite case? Forgot to use global when you probably should. Or in other words, local var ".." shadows global. Would this be useful?

x = 3


def set_x(n):
    x = n
    return x  # use x


print(set_x(5))
print(x)  # 3

r-downing avatar Apr 01 '25 00:04 r-downing