...

/

Puzzle 16: Explanation

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 wraps
def metrics(fn):
ncalls = 0
name = fn.__name__
@wraps(fn)
def wrapper(*args, **kw):
ncalls += 1
print(f'{name} called {ncalls} times')
return wrapper
@metrics
def inc(n):
return n + 1
inc(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.