[Tutor] Namespace Problem

bob bgailer at alum.rpi.edu
Sat Nov 5 03:31:38 CET 2005


At 05:47 PM 11/4/2005, Carroll, Barry wrote:
>I have a function that makes use of several global variables:
>
>##########
>Include struct

Did you mean "import"?

>ABC = 1
>DEF = 2
>xyz = 0
>def do_stuff(in_str):
>     hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
>     newstr = hdr+in_str

Works find for me. Is there anything else you are not showing us?

>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
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list