Browse Source

Decorator

pull/10/head
Jure Šorn 6 years ago
parent
commit
cef1ceae12
1 changed files with 7 additions and 4 deletions
  1. 11
      README.md

11
README.md

@ -608,11 +608,13 @@ def function_that_gets_passed_to_decorator():
``` ```
### Debugger Example ### Debugger Example
**"Wraps" decorator copies metadata of function func() to function out(). Without it `add.__name__` would return `'out'`.**
```python ```python
from functools import wraps from functools import wraps
def debug(func): def debug(func):
@wraps(func) # Copies func's metadata like name and doc to out. @wraps(func)
def out(*args, **kwargs): def out(*args, **kwargs):
print(func.__name__) print(func.__name__)
return func(*args, **kwargs) return func(*args, **kwargs)
@ -625,6 +627,7 @@ def add(x, y):
### LRU Cache ### LRU Cache
**Decorator that caches function's return values. All arguments must be hashable.** **Decorator that caches function's return values. All arguments must be hashable.**
```python ```python
from functools import lru_cache from functools import lru_cache
@ -634,10 +637,10 @@ def fib(n):
``` ```
```python ```python
>>> [fib(n) for n in range(16)] >>> [fib(n) for n in range(8)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] [0, 1, 1, 2, 3, 5, 8, 13]
>>> fib.cache_info() >>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) CacheInfo(hits=12, misses=8, maxsize=None, currsize=8)
``` ```
### Parametrized Decorator ### Parametrized Decorator

|||||||
100:0
Loading…
Cancel
Save