Python
Decorators
27 flashcards · answers and spaced-repetition review in the KnowCard app
What does @deco written above a function definition actually do to the name?
A decorator's wrapper is written as def wrapper(*args, **kwargs): and calls fn(*args, **kwargs). Why both the */** in the signature AND in the call?
What does this print?
```python
def with_timing(fn):
def wrapper(*a, **k):
return fn(*a, **k)
return wrapper
@with_timing
def nap():
"""sleep"""
print(nap.__name__)
```
What does functools.wraps do, and where do you put it?
What does this print?
```python
def a(f):
def w(): print("a"); f()
return w
def b(f):
def w(): print("b"); f()
return w
@a
@b
def g(): print("g")
g()
```
@a then @b above a function is equivalent to which single assignment?
Your decorator's wrapper works, but the decorated function's call returns None even though the original returns a value. What's the bug?
What does this print?
```python
def shout(f):
def w(*a, **k):
return f(*a, **k).upper()
return w
@shout
def greet(n):
return f"hi {n}"
print(greet("sam"))
```
A decorator that takes arguments, like @repeat(3), needs how many nested levels and why?
What's the difference in meaning between @deco and @deco() above a function?
How can a **class** be used as a decorator (like the book's CacheDecorator)?
What does this print?
```python
import functools
@functools.lru_cache
def f(n):
print("calc", n)
return n*n
f(3); f(3); f(4)
```
When does @functools.lru_cache give *wrong* results or fail outright?
What does this print?
```python
import functools
@functools.lru_cache(maxsize=20)
def fac(n):
r = 1
for i in range(2, n+1): r *= i
return r
[fac(x) for x in [7,5,7,5]]
print(fac.cache_info().hits)
```
Name three built-ins you already use that are actually decorators, and what each does to a method.
What does this print?
```python
class C:
@property
def val(self):
return 42
c = C()
print(c.val())
```
How does @dataclasses.dataclass above a class definition work, given decorators wrap functions?
What does functools.total_ordering require on the class, and what does it add?
What does this print?
```python
import functools
@functools.singledispatch
def mult(x): return x*2
@mult.register(str)
def _(x): return str(int(x)*2)
print(mult(5), mult("5"))
```
You keep calling send(host, port, user, msg) with the same first three values. What does functools.partial(func, *args, kwargs) give you, and what restriction hits you if you fix positional (not keyword) arguments?
With @functools.lru_cache(maxsize=None, typed=True), do calls f(2) and f(2.0) share one cache entry? And what does maxsize=None change?
Inside a class body you want two ready-made variants of a method — set_donald and set_goofy that call set_source with the author already fixed. Which functools helper builds them?
A test suite reuses an @lru_cache'd function across cases and gets stale results carried between tests. What method resets the cache, and what does it take?
The book's class-based CacheDecorator caches correctly and speeds things up. Why does the book warn you never to use it as a real cache?
Using functools.singledispatch, you want one implementation to serve BOTH str and float without writing the body twice. How?
singledispatch isn't general-purpose overloading like C++. What two hard limits does the book call out?
A consuming generator must be primed with next(gen) before you can .send() values to it. How does a consumer decorator eliminate that manual next() call?
Start learning today
Free to start — download the app or use it in your browser.
