[triangle-zpug] scope in nested function calls

Philip Semanchuk philip at semanchuk.com
Sun May 11 17:54:33 UTC 2008


On May 11, 2008, at 1:20 PM, Joseph Mack NA3T wrote:

>
> 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).


What you're calling "global" would, in Python terms, be a "module- 
level variable". e.g.:

#! /usr/bin/python

# The line below will be executed once when the module is initialized.
bar_value=42

def foo():
         global bar_value
         print "foo: bar_value  %d" %bar_value

def bar():
         bar_value=1
         print "bar: bar_value  %d" %bar_value
         foo()


foo()
bar()
foo()



This should print (untested):

foo: bar_value  42
bar: bar_value  1
foo: bar_value  1



HTH
Philp



More information about the triangle-zpug mailing list