In python if you define a global variable it's known to all functions without explicit passing and you can do e.g. this:
x=1
def func():
return x
I know this is normal behaviour, but it's also enabling unclean code because the interpreter doesn't tell you if you forget to pass a global variable to a function.
I'm usually writing scripts for data processing where usually all the code is in one file as data processing is a linear process. For the same reason I only use functions but not classes. However that way of designing leads to having lots of global variables and sometimes forgetting to pass all of them explicitely to functions.
Is there a way to have Python throw a warning when I use a global variable in a function without explicitely passing it?
I'm using Python 3.7.4 on IPython 7.7.0 in Spyder 3.7.
Unfortunately, no. In python, everything is an truly an object, so "globals" would include classes, functions and imported modules too.
However, you can check if a function uses global variables by something like
import inspect, warnings
y = 5
def f(x):
return x + y
def warn_me(func):
if inspect.getclosurevars(func).globals:
warning.warn(f'function {func.__name__} uses global variables')
warn_me(f)
For debugging purposes, you could make a script that walks through your files & functions and checks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With