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

by
Jeremy Canfield |
Updated: May 19 2025
| 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