Bootstrap FreeKB - Python (Scripting) - UnboundLocalError: local variable 'result' referenced before assignment
Python (Scripting) - UnboundLocalError: local variable 'result' referenced before assignment

Updated:   |  Python (Scripting) articles

Let's say something like this is being returned.

UnboundLocalError: local variable 'foo' referenced before assignment

 

Notice in this example that a local variable named 'foo' was referenced before assignment. Here is an example Python script that produces this error.

def my_function():
    try:
        foo = bar()
    except Exception as e:
        print("An error occurred")

    print(foo)

my_function()

 

This is why it's always recommended to error handle everything, perhaps like this.

def my_function():
  try:
    foo = bar()
  except Exception as exception:
    message = f"got the following exception when trying foo = bar() => {exception}"
    return { "result": "failed", "message": message }

  try:
    foo
  except Exception as exception:
    message = "got the following exception when trying foo => {exception}"
    return { "result": "failed", "message": message }

my_function_response = my_function()

print(f"my_function_response = {my_function_response}")

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 919fee in the box below so that we can be sure you are a human.