[triangle-zpug] scope in nested function calls
Joseph Mack NA3T
jmack at wm7d.net
Sun May 11 19:20:30 CEST 2008
I've just moved a piece of code out of a long function into another (lower
nested) function and I'd like the lower nested function to still access (write
to) variables in the calling function. I'm doing this for readability and so
that I can test a couple of different versions of the lower nested function by
commenting out calls in the calling function.
Here's an example piece of code
-------------------------------
#! /usr/bin/python
def foo():
print "foo: bar_value %d" %bar_value
def bar():
bar_value=1
print "bar: bar_value %d" %bar_value
foo()
#main()
bar()
---------
the output is
# ./test_scope.py
bar: bar_value 1
Traceback (most recent call last):
File "./test_scope.py", line 12, in ?
bar()
File "./test_scope.py", line 9, in bar
foo()
File "./test_scope.py", line 4, in foo
print "foo: bar_value %d" %bar_value
NameError: global name 'bar_value' is not defined
-------------
I can't use "global bar_value" inside foo(), since bar_value isn't global.
bar_value isn't local, enclosed, global or built-in (AFAIK).
Is there a way to write to variables in a calling function? (If I have to pass
all variables as parameters, I'd rather leave the code inside the original
function).
Thanks Joe
--
Joseph Mack NA3T EME(B,D), FM05lw North Carolina
jmack (at) wm7d (dot) net - azimuthal equidistant map
generator at http://www.wm7d.net/azproj.shtml
Homepage http://www.austintek.com/ It's GNU/Linux!
More information about the TriZPUG
mailing list