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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With