Can global variable be passed into Python function?

Peter Otten __peter__ at web.de
Fri Feb 21 08:34:47 CET 2014


Sam wrote:

> I need to pass a global variable into a python function. However, the
> global variable does not seem to be assigned after the function ends. Is
> it because parameters are not passed by reference? How can I get function
> parameters to be passed by reference in Python?

If the variable you want to process is always the same global variable you 
can declare it:

>>> x = 0
>>> def inc_x():
...     global x
...     x += 1
... 
>>> x
0
>>> inc_x()
>>> x
1
>>> inc_x(); inc_x()
>>> x
3

If you want to change ("rebind") varying global names you have to be 
explicit:

>>> def inc(x):
...     return x + 1
... 
>>> x = 0
>>> x = inc(x)
>>> y = 0
>>> y = inc(y)
>>> y = inc(y)
>>> x, y
(1, 2)

Then there are ugly hacks that make your code hard to follow. Don't use 
these:

>>> def inc(name):
...     globals()[name] += 1
... 
>>> inc("x")
>>> inc("x")
>>> x
3

>>> def inc(module, name):
...     setattr(module, name, getattr(module, name) + 1)
... 
>>> import __main__
>>> inc(__main__, "x")
>>> inc(__main__, "x")
>>> inc(__main__, "x")
>>> x
6





More information about the Python-list mailing list