To make sure that the correct variable is used, you need to limit the scope of the search. Inside the function, Python will look for the arguments defined in the string, and then args and kwargs . After that, he will look outside the function. This can cause annoying errors if the function depends on a global variable that changes elsewhere.
To avoid accidentally using a global variable, you can define a function with a keyword argument for the variables that you intend to use:
def test(x=None): y=x+2
I assume that you do not want to do this for many variables. However, this will stop the function from using global variables.
Actually, even if you want to use a global variable in a function , I think it's best to make it explicit:
x = 2 def test(x=x): y=x+2
In this example, x = 2 will be used for the function, regardless of what happens to the global value of x after that. Inside the function x , the value it had at compile time is fixed.
I started passing global variables as keyword arguments after you burned a couple of times. I think this is usually considered good practice?
Will martin
source share