Description
When all IP-check URLs fail (e.g., proxy is down), verify_ip_address() raises:
UnboundLocalError: cannot access local variable 'exception' where it is not associated with a value
instead of the intended InvalidIP exception.
Root cause
In Python 3, except ... as var deletes var when the except block exits (PEP 3110). So after the last iteration's except block runs, exception is deleted, and line 120 can't access it.
# ip.py lines 104-120
exception = None # initial assignment
for url in URLS:
try:
...
except (...) as exception: # Python 3 deletes 'exception' after this block exits
pass
raise InvalidIP(f"Failed to get IP address: {exception}") # UnboundLocalError
Fix
last_exception = None
for url in URLS:
try:
...
except (requests.exceptions.ProxyError, requests.RequestException, InvalidIP) as exception:
last_exception = exception
raise InvalidIP(f"Failed to get IP address: {last_exception}")
Reproduction
Call verify_ip_address() with a proxy that can't reach any of the IP-check URLs (all 5 must fail).
Description
When all IP-check URLs fail (e.g., proxy is down),
verify_ip_address()raises:instead of the intended
InvalidIPexception.Root cause
In Python 3,
except ... as vardeletesvarwhen the except block exits (PEP 3110). So after the last iteration's except block runs,exceptionis deleted, and line 120 can't access it.Fix
Reproduction
Call
verify_ip_address()with a proxy that can't reach any of the IP-check URLs (all 5 must fail).