Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
62 changes: 62 additions & 0 deletions decorators.py
Original file line number Diff line number Diff line change
@@ -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"<u>{func()}</u>"
return wrapper

def emphasis(func):

@wraps(func)
def wrapper():
return f"<em>{func()}</em>"
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))