Default functions values are calculated during function creation time, so even if you change the value of x
it is not going to be changed in the function.
From docs:
Default parameter values are evaluated when the function definition is
executed. This means that the expression is evaluated once, when the
function is defined, and that the same “pre-computed” value is used
for each call.
Read: Using mutable
objects as default value can lead to unexpected results.
If you want to access a global value then simply do:
def func():
return x**2
Or better pass it explicitly:
def func(y):
return y**2
Another reason why not to use global variables inside function:
>>> x = 10
>>> def func():
... print x
... x = 5
...
>>> func()
Traceback (most recent call last):
func()
File "<ipython-input-5-ab38e6cadf6b>", line 2, in func
print x
UnboundLocalError: local variable 'x' referenced before assignment
Using classes
:
class A:
x = 5
@staticmethod
def func():
return A.x**2
...
>>> A.func()
25
>>> A.x = 10
>>> A.func()
100