[triangle-zpug] scope in nested function calls

bob gailer bgailer at gmail.com
Sun May 11 23:24:57 CEST 2008


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).
>
> Thanks Joe
>
First let's note that the functions are not nested. Nested would look like:
def bar():
  bar_value = 3
  def foo():
    print bar_value
  foo()
and then the /reference /to bar_value would work (but not assignment).

To do what you are asking you'd need to make bar_value global, or create 
a class and use class properties.

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC





More information about the TriZPUG mailing list