Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 886
Matt Vukas Avatar asked Dec 26 '22 12:12

Matt Vukas


1 Answers

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.

like image 103
wim Avatar answered May 10 '23 02:05

wim