Python 3: UnboundLocalError: local variable referenced before assignment
To prevent UnboundLocalError
, the secret is in scope declaration. Declare a variable as global
within a function if you're modifying a global variable. Alternatively, use nonlocal
for variables in nested functions.
By simply declaring the scope with global
/ nonlocal
before assignment, you can sidestep that pesky error.
From Understanding to Mastery: UnboundLocalError
UnboundLocalError
is Python's way of saying, "This variable? Never heard of it before!" It occurs when a local variable is referenced before its declaration or initialization. Let's demystify this common error.
Tip: Curb the global enthusiasm!
Global
variables that are modified inside functions can create debugging nightmares, like the monster under your coder's bed. Instead, keep it tidy: pass variables as parameters and return the modified values.
Digging deeper: The finer nuances of globals and nonlocals
Challenging situations call for challenging solutions. Meet nonlocal
, used in nested functions. This keyword ensures that the variable is borrowed from the enclosing scope, not from the local or global community. This tool is native to the Python 3 ecosystem.
Understanding global and nonlocal difference
Question: When to use global
, when to opt for nonlocal
?
Answer:
global
is for top-of-the-chart variables defined at the top-level of your code.nonlocal
is for under-the-shadow variables in a nested function, in need to connect to its parent function.
Syntax: Beauty is in whitespaces
Grammar nazism is real! Keep a hawk's eye on indentation and syntax. Python is an unforgiving beast when it comes to code structure. An incorrectly placed indentation can flag an UnboundLocalError faster than you can say Python!
When variables play truant
Consider all possibilities including "Schrodinger's variable" scenario where variables may not be set or initialized. Hint: Use conditions and default values to protect your code from UnboundLocalError
.
Python 2 vs Python 3: A sports match!
On the off chance you are playing with Python 2, watch out for quirk alerts with the global statement. Feel the smooth sailing with Python 3 and its shining knight: the nonlocal
statement.
Handling Globals and Nonlocals: Beyond the basics
Local is the new global
Go local! Make local copies of globals within functions. This saves the world, or at least the global space, from adverse side effects.
The nonlocal secret weapon
nonlocal
is a clarity champ, indicating you're borrowing from an enclosing scope, making your code leaner and meaner.
Alternatives to global
Break the barriers. Instead of global
, embrace other design patterns like classes or factory functions. They contain state more elegantly.
Mutable globals: Handle with care!
Mutable global variables like lists or dictionaries are like a double-edged sword. Without a global
declaration, you can still mutate their state inside a function, leading to odd results.
Non-obvious tricks and tips
Scopes and namespaces
Remember LEGB (Local, Enclosing, Global, Built-in), the order Python follows to look up variable names.
Thinking beyond basics
Functions are not just about returning values! They can also return functions. Dealing with nested closures? The nonlocal
keyword is your best friend for state persistence.
Debugging chronicles
Battling UnboundLocalError? Check for variables' scope, ensure assignment before access, and avoid overlapping variable names in different scopes.
A note on performance
Local variables are faster to access than globals which also spins off cleaner, maintainable code.
Conditional wisdom
Think ahead when modifying globals under certain conditions. Pre-initialize these variables as None
or a default value outside the function.
Was this article helpful?