Python3 UnboundLocalError: local variable referenced before assignment

Viewed 807

I wrote the following code in python3 which runs perfect:

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
message = ""
run_again = False

try:
    response = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)
except requests.exceptions.RequestException as e:
    message = "Connection Failed!"
    run_again = True

if "משתמש לא מזוהה" in response.text:
    message = "User Was Logged Out Automatically!"

But when I cut the internet, I get the following error:

    if "משתמש לא מזוהה" in response.text:
UnboundLocalError: local variable 'response' referenced before assignment

how can I solve this?

3 Answers

Without the internet, an exception will be raised on this line.

response = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)

That would make response undefined. One way to resolve this is to move the if statement to the try block

try:
    response = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)
    if "משתמש לא מזוהה" in response.text:
       message = "User Was Logged Out Automatically!"
except requests.exceptions.RequestException as e:
    message = "Connection Failed!"
    run_again = True

Try initializing the response variable outside the try/except code.

If requests.get() raises an exception, then you can't use response since it won't be assigned.

You can instead define a function, e.g. handle_response and call that function within the try block.

def handle_response(response):
   if "משתמש לא מזוהה" in response.text:
        message = "User Was Logged Out Automatically!"

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
message = ""
run_again = False

try:
    response = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)
    handle_response(response)
except requests.exceptions.RequestException as e:
    message = "Connection Failed!"
    run_again = True

The handle_response function will only be called if the requests.get() does not raise any exceptions.

Related