Puzzle 16: Explanation
Let’s look at the scope of variables in Python and the cause of the `UnboundLocalError` exception.
We'll cover the following...
Try it yourself
Try executing the code below to verify the result:
Press + to interact
from functools import wrapsdef metrics(fn):ncalls = 0name = fn.__name__@wraps(fn)def wrapper(*args, **kw):ncalls += 1print(f'{name} called {ncalls} times')return wrapper@metricsdef inc(n):return n + 1inc(3)
Explanation
When we have a variable, or name, in Python like cart = [‘lamp’]
), we can do two operations:
- Mutate the variable by changing the object that the variable is pointing to (
cart.append(‘mug’)
).
Access this course and 1400+ top-rated courses and projects.