Search⌘ K
AI Features

Puzzle 16: Explanation

Explore how Python variables can be mutated or rebound within different scopes. Understand the LEGB rule, the impact of immutability, and how to use nonlocal and global keywords effectively in Python puzzles.

We'll cover the following...

Try it yourself

Try executing the code below to verify the result:

Python 3.8
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’)).
  • Rebind the variable by having the variable point to another
...