TPT (Tiny Python Tip): Global

by Noah Gift

Most people forget that python is both procedural and Object Oriented. If you find yourself wanting to use a procedural, Bash style of programming with Python, take a look at the global statement.

It lets you do something like this, because without the :

In [34]: x = 1; y = 2

In [35]: def func():
....: global x, y
....: print "X = %s, Y = %s, in func" % (x,y)
....:
....:

In [36]: func()
X = 1, Y = 2, in func


Here is an even better example, based on the comment by Ant, as the top example was too vague, probably because I was trying to make the example too "tiny" :) That is a challenge, to make a tip tiny, yet explicit.


In [46]: x = 1; y = 2; z = "out here"

ln [47] def func():
....: global x,y,z
....: print "X = %s, Y = %s, in func. Z says: %s " % (x,y,z)
....: x = 1000;y=1000;z="in here"
....: print "X = %s, Y = %s, in func. Z says: %s " % (x,y,z)

In [48]: func()
X = 1, Y = 2, in func. Z says: out here
X = 1000, Y = 1000, in func. Z says: in here



I should also say, thanks to Tres, who showed me this tip to begin with!

3 Comments

Ant
2007-12-17 00:41:41
You only need the global statement if you need to assign to the x and y. The above can be more simply achieved without the "global x, y" line. A better example may be:



>>> x = "Blah"
>>> def pp():
... global x
... x = "Hello There!"
...
>>> print x
Blah
>>> pp()
>>> print x
Hello There!
Noah Gift
2007-12-17 02:42:57
Ant/I suppose my example was a pinch too vague, your right. As if you didn't include the global in the func, above you would get a referenced before assignment error, which is perhaps not instructive enough.


Let me add a little bit more based on your suggestion to the top.

Pento
2007-12-17 02:55:26
Thanks for the tip