Puzzle 16 Call Me Maybe

Python Brain Teasers — by Miki Tebeka (25 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Where’s Waldo? | TOC | Endgame 👉

metrics.py

​ ​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)

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will raise an UnboundLocalError exception.

images/hline.png

When you have a variable (name) in Python (say, cart = [’lamp’]), you can do two operations:

Mutate
Change the object the variable is pointing to (e.g., cart.append(’mug’))

Rebind
Have the variable point to another object (e.g., cart = [’carrots’])

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.