Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get a warning when using a global variable in a function without expicitely passing it to the function?

Tags:

python

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.

like image 933
Khris Avatar asked Sep 14 '25 13:09

Khris


1 Answers

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.

like image 139
blue_note Avatar answered Sep 17 '25 02:09

blue_note