diff --git a/README.md b/README.md index 2fcd568..8f50ae9 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Welcome everyone to contribute to this project! - [bubbleSort.py](https://github.com/Henry-Jia/python-tools/blob/master/bubbleSort.py): bubble sort - [chess.py](https://github.com/Henry-Jia/python-tools/blob/master/chess.py): a chess game - [circle_using_square.py](https://github.com/Henry-Jia/python-tools/blob/master/circle_using_square.py): circle using number of squares +- [decorators.py](https://github.com/Henry-Jia/python-tools/blob/master/decorators.py): A start guide to use simple and argument decorators - [draw_PeppaPig.py](https://github.com/Henry-Jia/python-tools/blob/master/draw_PeppaPig.py): draw PeppaPig with Python - [electricity_consumption.py](https://github.com/Henry-Jia/python-tools/blob/master/electricity_consumption.py): calculates electricity consumed - [factorial.py](https://github.com/Henry-Jia/python-tools/blob/master/factorial.py): a simple program to calculate the factorial of a number diff --git a/decorators.py b/decorators.py new file mode 100644 index 0000000..ed005ea --- /dev/null +++ b/decorators.py @@ -0,0 +1,62 @@ +""" Decorator Samples """ +from functools import wraps + +""" Simple Decorator: does not decorate functions with arguments """ +def uppercase(func): + + @wraps(func) + def wrapper(): + return func().upper() + return wrapper + +def underline(func): + + @wraps(func) + def wrapper(): + return f"{func()}" + return wrapper + +def emphasis(func): + + @wraps(func) + def wrapper(): + return f"{func()}" + return wrapper + +# Those wraps decorators, are responsible for transmit function metadata to wrapped ones +# Metadata Like docstrings and name + +""" Argument Decorator: Handle Args and Kwargs to wrapped functions """ + +def trace(func): + + @wraps(func) + def wrapper(*args, **kwargs): + print(f'LOG: calling {func.__name__}() with {args}, {kwargs}') + original_result = func(*args, **kwargs) + print(f'LOG: {func.__name__}() returned {original_result!r}') + return original_result + return wrapper + +""" +Multiple simple decorators usage. +Note that the activation order is bottom to top. +""" +@emphasis +@underline +@uppercase +def hello_world(): + return f"Hello World!" + +@trace +def hello_date(day, month, year): + return f"Hello, it's {day} of {month} from {year}!" + + +if __name__ == "__main__": + # Hello World will be affected by all three decorators. + print(hello_world()) + + # Hello date is under trace decorator, commonly used to Log Method executions. + # Also this could be usefull when seeking for coverage metrics. + print(hello_date('friday', 'may', 2019))