Yetti
Yetti

Reputation: 327

Variable referenced before assignment in this code

I have the following code:

try:
    connSock = socket(AF_INET, SOCK_STREAM)
    connSock.connect((tgtHost, tgtPort))
except:
    pass
finally:
    connSock.close()

Pycharm says that:

Local variable 'connSock' might be referenced before assignment on connSock.close() line

How is that even possible?

Am I missing something?


UPDATE:

socket() function may raise exception if your OS run out of descriptors

Upvotes: 1

Views: 899

Answers (3)

Alex Riley
Alex Riley

Reputation: 176750

If the try block raises an error (specifically in the first line connSock = socket(AF_INET, SOCK_STREAM)), connSock won't be defined when the finally block is executed.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121466

If the socket() call on the second line raises an exception, then connSock is never bound.

Sockets can be used as context managers, use that to your advantage:

try:
    with socket(AF_INET, SOCK_STREAM) as connSock:
        connSock.connect((tgtHost, tgtPort))
except socket.error:
    pass

This'll close the socket when the with block is exited, without having to reference it, and only if the socket() call actually succeeded.

Note that you should rarely use a blanket except: pass. Better to catch specific exceptions.

Upvotes: 8

hlt
hlt

Reputation: 6317

socket(AF_INET, SOCK_STREAM) might throw an exception, so that connSock never gets assigned. Then, connSock.close() can't possibly work.

Upvotes: 3

Related Questions