1def our_decorator(func):
2 def function_wrapper(x):
3 print("Before calling " + func.__name__)
4 func(x)
5 print("After calling " + func.__name__)
6 return function_wrapper
7
8@our_decorator
9def foo(x):
10 print("Hi, foo has been called with " + str(x))
11
12foo("Hi")
13
1#Decorator are just function that take function as first
2#parameter and return a function
3def logging(f):
4 def decorator_function(*args, **kwargs):
5 print('executing '+f.__name__)
6 return f(*args, **kwargs)
7 return decorator_function
8#Use it like this
9@logging
10def hello_world():
11 print('Hello World')
12#calling hello_world() prints out:
13#executing hello_world
14#Hello World
1# Decorator with arguments
2import functools
3
4# First function takes the wanted number of repetition
5def repeat(num_times):
6 # Second function takes the function
7 def decorator_repeat(func):
8 # Third function, the wrapper executes the function the number of times wanted
9 # functools decorator to print the true name of the function passed instead of "wrapper"
10 @functools.wraps(func)
11 def wrapper(*args, **kwargs):
12 for _ in range(num_times):
13 result= func(*args, **kwargs)
14 return result
15 return wrapper
16 return decorator_repeat
17
18# Our function using the decorator
19@repeat(num_times= 3)
20def greet(name):
21 print(f"Hello {name}")
22
23greet("thomas")
1import functools
2
3# A decorator is a Higher order function "_with_logging"
4# It takes the function to be decorated as its argument
5# In order to pass in some arbitrary arguments, it must be wrapped into
6# another HOF (Higher order function) that will receive the inputs
7def with_logging(level=logging.DEBUG, msg = None):
8 def _with_logging(fn):
9 # 'wraps' is a HOF that will give fn's name and docs to decorated_fn i.e.
10 # decorated_fn.__name__ = fn.__name__
11 # help(decorated_fn) = help(fn)
12 @functools.wraps(fn)
13 def decorated_fn(*args, **kwargs):
14 res = fn(*args, **kwargs)
15 print("\n***************", f"\n{msg}", "\nExecuting with Args: ", *args, **kwargs)
16 logging.log(level, res)
17 return res
18 return decorated_fn
19 return _with_logging
20
21# Used this way
22@with_logging(level=logging.DEBUG, msg="Some awesome comment")
23def hello_world(name):
24 return f'Hello World {name}'
25
26# Results after calling hello_world("John")
27#
28# ***************
29# Some awesome comment
30# Executing with Args: John
31# Hello World John
32
1def deco(func):
2 def wrap(lst):
3 x = [1 if i % 2 == 0 else 0 for i in lst]
4 return x
5 func(lst)
6 return wrap
7
8@deco
1from functools import wraps
2def debug(func):
3 @wraps(func)
4 def out(*args, **kwargs):
5 print('hello world')
6 return func(*args, **kwargs)
7 return out
8
9@debug
10def add(x, y):
11 return x + y