From 922f6c0d33c26ba98a40e0c75c8c74188687f9b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 20:27:51 +0100 Subject: [PATCH] Decorator --- README.md | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 93ee1f0..1182031 100644 --- a/README.md +++ b/README.md @@ -605,12 +605,12 @@ def function_that_gets_passed_to_closure(): ... ``` -#### Debugger example: +### Debugger Example ```python from functools import wraps def debug(func): - @wraps(func) # Needed for metadata copying (func name, ...). + @wraps(func) # Copies func's metadata like name and doc to out. def out(*args, **kwargs): print(func.__name__) return func(*args, **kwargs) @@ -638,6 +638,24 @@ def fib(n): CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) ``` +### Parametrized Decorator +```python +def debug(print_result=False): + def inner_decorator(func): + @wraps(func) + def out(*args, **kwargs): + result = func(*args, **kwargs) + print(func.__name__, result if print_result else '') + return result + return out + return inner_decorator + +@debug(print_result=True) +def add(x, y): + return x + y +``` + + Class ----- ```python