Index
Subject
: Re: LUG: Modifying global variables in Python
From
: Kevin Hunter <hunteke@earlham.[redacted]>
Date
: Wed, 28 Jul 2010 22:14:12 -0600
Parent
At 9:16pm -0600 Wed, 28 Jul 2010, Daniel Underwood wrote:
> From what I've read in forums, it seems that Python 2.6 does not
> have a straight-forward way to modify global variables inside a
> function.
It does. However, I highly, highly, highly suggest you stay away from
globals use and modification. The minute you start down the path, your
code will be that much harder to maintain. For a Q&D script, fine, but
if you *ever* start writing scripts that involve importing other
scripts, you will kick yourself for messing with globals. Put
differently, if we ever cross paths and you ask for help, the minute I
see globals, you're on your own.
> This example will put it more clearly:
> <http://codepad.org/w7Aw2SpD>
You want to tell the function that 'a' refers to the global variable:
a = 5
def func ( ):
global a
print a
> The best "fix" I've found, is to do something like this:
> <http://codepad.org/U1Ct7AFO>
This is a different beast altogether called a 'closure'. Very roughly,
and not quite correctly, a closure is a way to "snapshot" data at
runtime. In this trivial case it's not much, but you can do much more
powerful constructs like return functions or classes dynamically
tailored to fit a need.
def func ( msg ):
def wrapped ( *args, **kwargs ):
# do something
print msg
val = func( 'instantiated' + str(time()) )
# ... more calculation, then, at a later date:
val() # executes the 'wrapped' function with the snapshot of
# the msg passed above.
> Is there a simpler way to overcome this limitation?
The python keyword 'global'.
If you haven't discovered tab-completion, you probably want to install
ipython ("Interactive Python"). It's a great tool for dynamically
introspecting your python code:
#!/usr/bin/env python
a = 'test'
import IPython
IPython.Shell.IPShellEmbed()()
# At the ensuing prompt, type 'a<tab><tab>'
Where that's you hitting the tab key, not typing literally.
HTH,
Kevin
Replies
: