[Tutor] Namespace Problem
Carroll, Barry
Barry.Carroll at psc.com
Sat Nov 5 02:47:20 CET 2005
I have a function that makes use of several global variables:
##########
Include struct
ABC = 1
DEF = 2
xyz = 0
# Other variables
def do_stuff(in_str):
hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
newstr = hdr+in_str
# rest of code snipped
##########
When I run the program containing this code I get this error:
>>>>>>>>>
Traceback (most recent call last):
File "sample.py", line 43, in ?
ret_data = do_stuff(data)
File "sample.py", line 17, in do_stuff
hdr = struct.pack('@2BH', ABC|DEF,xyz,len(in_str))
UnboundLocalError: local variable 'xyz' referenced before assignment
>>>>>>>>>
The error goes away if I include a 'global' statement at the top of the
function:
##########
def do_stuff(in_str):
global xyz
hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
##########
Why does the interpreter choke on xyz and not on ABC or DEF?
Barry
More information about the Tutor
mailing list