What is an elegant / Pythonic way to keep variables in scope, but also exceptions?

I have been using Python for several months and I really like it. I also like how there is usually one β€œpythonic” way of handling common programming problems.

In the code that I wrote when I make calls for network functions and should handle exceptions, I continue to work with this template, which I end up writing:

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

if proxyTest:
    ...

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

, , . ?

+4
3

, else:

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

except.

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

, , .

+6

"" except:

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

/ , , , .

+5

if proxyTest: 

try, -.

-1

Source: https://habr.com/ru/post/1529440/


All Articles