non-blocking sockets and generators

Andrew Bennetts andrew-pythonlist at puzzling.org
Sat May 24 07:00:32 EDT 2003


On Sat, May 24, 2003 at 08:39:10PM +1000, Gary Stephenson wrote:
> 
> I'm playing around with combining non-blocking sockets with generators -
> which is probably really stupid 'coz I don't know terribly much about either
> but, hey ..  I _am_ learning....
> 
> Anyway, I suspect my first question has nothing to do with non-blocking
> sockets _or_ generators, albeit that both appear in the code.  Why does this
> :
> 
>     def socketAccept( self, s ) :
>         while True :
>             try :
>                 ( sock, addr ) = s.accept()
>             except :
>                 yield None
>             self.addThread( self.createThread( sock, addr ) )
> 
> yield the following error ? (running under Pythonwin) :
> 
>     self.addThread( self.createThread( sock, addr ) )
> UnboundLocalError: local variable 'sock' referenced before assignment

That is correct.  Look at what happens if the first run through your
generator fails on the "s.accept()" -- it will raise and exception, and
yield None.  Then when you call the generator again, it will will hit the
next line, and BOOM!  At no point in this sequence did anything get assigned
to sock, so it fails.

I *think* you might want this idiom:

    try:
        something_that_can_fail()
    except ItFailed:
        handle_error()
    else:
        handle_success()

i.e. put that last line in an else block.

> Also, I'd like to be a touch more specific ;-) in the except clause, but I
> can't seem to figure out the appropriate exception class to use.  The socket
> docs talk about non-blocking sockets raising
> "a 'error' exception", but when I tried to use "except error : "  I got
> 
> NameError: global name 'error' is not defined
> 
> What exception class (if any) should be used to catch the non-blocking
> socket's exception?

The 'error' class is defined in the socket module, so do:

    except socket.error, e:
        # ....

-Andrew.






More information about the Python-list mailing list