C-style static variables in Python?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Apr 2 20:40:28 CEST 2010


On Fri, 02 Apr 2010 16:08:42 +0000, kj wrote:

> Other responses advocated for global variables.  I avoid them in
> general, 

In general this is wise, but remember that because Python globals are not 
globally global, but local to a single module, they're safer than globals 
in other languages. Still, it's better to avoid them when possible.


> and doubly so in Python, because I find Python's shenanigans
> with globals mystifying (this business of becoming silently local if
> assigned to); 

Globals don't become local when assigned to. You can shadow a global with 
a local of the same name, but the global remains untouched:

>>> myglobal = 42
>>> def test():
...     myglobal = 0  # shadow the global with a new local
...
>>> test()
>>> myglobal
42

I find this behaviour perfectly natural, and desirable: it means I can 
assign to locals without worrying whether or not I'm about to stomp all 
over a global and destroy it. The alternative behaviour would be 
disastrous:

>>> def f(x): return x+1
... 
>>> def test():
...     f = 'spam'
...
>>> test()
>>> f(2)  # this doesn't happen
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable



-- 
Steven



More information about the Python-list mailing list