Search code examples
pythonpython-3.xslack-api

How to solve UnboundedLocalError: local variable referrenced before assignment


I know articles are existing for this similar issue. But I don't see a case of a global variable here, I have not used this as a global variable in code. So it has confused me and stuck for a while.

Function:

def slack(inform):
   
    env_name = libs.get_env_name()

    if env_name == 'ISPROD':
        web_hook_url = 'https://hooks.slack.com/services/XXXXXXXX/XXXXXXXX/XXXXXXXX'
    elif env_name == 'DEV':
        web_hook_url = 'https://hooks.slack.com/services/XXXXXXXX/XXXXXXX/XXXXXXXX'
    msg = {'text':inform}
    requests.post(web_hook_url,data=json.dumps(msg))

web_hook_url is not declared globally anywhere outside this function. What else could be causing this?

Error says:

[ERROR] UnboundLocalError: local variable 'web_hook_url' referenced before assignment
Traceback (most recent call last):

  File "main.py", line 402, in pull_data
    transfer_send(
  File "main.py", line 314, in transfer_send
    slack(pass_mess)
  File "main.py", line 111, in slack
    requests.post(web_hook_url,data=json.dumps(msg))

Solution

  • Try add print(env_name)

    def slack(inform):
       
        env_name = libs.get_env_name()
        print(env_name)
        if env_name == 'ISPROD':
            web_hook_url = 'https://hooks.slack.com/services/XXXXXXXX/XXXXXXXX/XXXXXXXX'
        elif env_name == 'DEV':
            web_hook_url = 'https://hooks.slack.com/services/XXXXXXXX/XXXXXXX/XXXXXXXX'
        msg = {'text':inform}
        requests.post(web_hook_url,data=json.dumps(msg))
    

    and see what value it is, because it's look like it has other value that you trying to check in if elif block

    if you want just to avoid this error:

    if env_name == 'ISPROD':
            web_hook_url = 'https://hooks.slack.com/services/XXXXXXXX/XXXXXXXX/XXXXXXXX'
    elif env_name == 'DEV':
            web_hook_url = 'https://hooks.slack.com/services/XXXXXXXX/XXXXXXX/XXXXXXXX'
    else:
         web_hook_url = None