Matt Vukas
Matt Vukas

Reputation: 3295

What is the elegant/Pythonic way to keep variables in scope, yet also catch exceptions?

I've been using Python for a few months now, and I love it so far. I also like how there is usually a single, "Pythonic" way to handle common programming problems.

In code I've been writing, as I make calls to network functions and have to handle exceptions, I keep running into this template of sorts that I end up writing:

proxyTest = None
try:
    proxyTest = isProxyWorking(proxy)
except TimeoutError:
    break

if proxyTest:
    ...

This is my way of declaring proxyTest so that it is in scope when I need to use it, yet also calling the function that will return a value for it inside of the proper exception handling structure. If I declare proxyTest inside of the try block, it will be out of scope for the rest of my program.

I feel like there has to be a more elegant way to handle this, but I'm not sure. Any suggestions?

Upvotes: 4

Views: 89

Answers (3)

wim
wim

Reputation: 362756

You have a couple of better options, continue your flow control in the else block:

try:
    proxyTest = isProxyWorking(proxy)
except TimeoutError:
    break
else:
    #proxyTest is guaranteed to be bound here

Or handle the failure case in the except block.

try:
    proxyTest = isProxyWorking(proxy)
except TimeoutError:
    proxyTest = None
#proxyTest is guaranteed to be bound here

Whichever is better depends on context, I think.

Upvotes: 6

Corley Brigman
Corley Brigman

Reputation: 12401

The obvious alternative would be to do the 'false' initialization in the except block:

try:
    proxyTest = isProxyWorking(proxy)
except TimeoutError:
    proxyTest = None

Whether this is easier/more appropriate than your constructions depends on how complicated the logic is in the middle, though.

Upvotes: 5

Colin Bernet
Colin Bernet

Reputation: 1394

I would put the code after

if proxyTest: 

in the try block, just after binding proxyTest.

Upvotes: -1

Related Questions