简体   繁体   中英

why am I getting local variable referenced before assignment?

I'm getting an error that I spent hours trying to understand why it's happening but I can't figure it out.

following is my code, it works fine without any issue until I disconnect the internet (that is why I made the exception to keep retrying when internet disconnects), when the internet disconnects the exception will keep calling the function and when the internet is back it will continue the function but then throw some errors: [Errno -2] Name or service not known UnboundLocalError: local variable 'ip' referenced before assignment

from time import sleep
from requests_html import HTMLSession

public_ip = ""

def get_ip():
    global public_ip
    session = HTMLSession()

    try:
        ip = session.get('https://api.ipify.org').text
    except:
        print("Exception started... Retrying")
        sleep(10)
        get_ip()

    if ip == public_ip:
        print("It's the same")
    else:
        print("new IP")
        print("Old " + public_ip)
        print(ip)
        public_ip = ip
        print("new " + public_ip)


while True:
    get_ip()
    sleep(10)

When there is no internet, the assignement of the variable ip doesnt work and that's why you get the error, try to initialize the variable ip before the try statement:

def get_ip():
global public_ip
session = HTMLSession()
ip = ""
try:
    ip = session.get('https://api.ipify.org').text
except:
    print("Exception started... Retrying")
    sleep(10)
    get_ip()
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM