[Tutor] Namespace Problem

Kent Johnson kent37 at tds.net
Mon Nov 7 22:26:39 CET 2005


Carroll, Barry wrote:
> Bob:
> 
> Yes I did mean 'import' and yes there is more to the function.  Here is the
> entire program.  
> 
> ########################
> import socket
> import struct
> 
> # data packet flags
> ABC = 1
> DEF = 2
> GHI = 4
> JKL = 8
> seq = 0
> 
> buf = 8192 # This is the max_packet_size defined in the SocketServer module
> addr = ('localhost', 12345) # Host and port used by the server
> 
> def do_stuff(in_str):
>     hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str))
>     newstr = hdr+in_str
>     if(sock.sendto(newstr,addr)):
>         response = sock.recv(buf)
>         flags, retseq, dlen = struct.unpack('@2BH', response[:4])
>         print "flags: 0x%X, retseq: %u, dlen: %u" % (flags, retseq, dlen)
>         response = response[4:]
>         rsphdr=eval(response[:response.find(')')+1])
>         response = response[response.find(')')+2:]
>         resptupl = (rsphdr, response)
>         seq += 1

The above statement binds a value to the name 'seq'. If a name is bound anywhere within a block,  the compiler treats it as a local name and it will not be looked up in the global namespace. When the struct.pack() line is executed, seq is not bound in the local namespace and you get an error. The solution is to include 'global seq' in do_stuff(); this tells the compiler that seq should always be treated as a global name even though it is bound in the current block.

This a little bit subtle because you are using seq += 1. Still this is binding a new value to seq and you need to declare it global.

Kent

>     return resptupl
> 
> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> 
> def_msg = "===Enter message to send to server===";
> print "\n",def_msg
> 
> # Send messages
> while (1):
>     data = raw_input('>> ')
>     if not data:
>         break
>     else:
>         print "Sending message '",data,"'"
>         ret_data = do_stuff(data)
>         print "Got back: ", ret_data
> 
> sock.close( )
> ########################
> 
> Here is a trace of program execution.  
> 
> 
> ===Enter message to send to server===
> 
>>>send some data
> 
> Sending message ' send some data '
> Traceback (most recent call last):
>   File "./bgctest.py", line 40, in ?
>     ret_data = do_stuff(data)
>   File "./bgctest.py", line 15, in do_stuff
>     hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str))
> UnboundLocalError: local variable 'seq' referenced before
> assignment>>>>>>>>>>>>>>>>>>>>>>>>
> 



More information about the Tutor mailing list