Last active
August 12, 2020 17:31
-
-
Save justinmklam/5f9016be892808690f7c950e836ba266 to your computer and use it in GitHub Desktop.
Demo in using decorators to minimize redundant code. Source: https://medium.com/swlh/handling-exceptions-in-python-a-cleaner-way-using-decorators-fae22aa0abec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def exception_handler(func): | |
def inner_function(*args, **kwargs): | |
try: | |
func(*args, **kwargs) | |
except TypeError: | |
print(f"{func.__name__} only takes numbers as the argument") | |
return inner_function | |
@exception_handler | |
def area_square(length): | |
print(length * length) | |
@exception_handler | |
def area_circle(radius): | |
print(3.14 * radius * radius) | |
@exception_handler | |
def area_rectangle(length, breadth): | |
print(length * breadth) | |
area_square(2) | |
area_circle(2) | |
area_rectangle(2, 4) | |
area_square("some_str") | |
area_circle("some_other_str") | |
area_rectangle("some_other_rectangle") | |
# Output: | |
# 4 | |
# 12.568 | |
# 8 | |
# area_square only takes numbers as the argument | |
# area_circle only takes numbers as the argument | |
# area_rectangle only takes numbers as the argument |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def area_square(length): | |
try: | |
print(length**2) | |
except TypeError: | |
print("area_square only takes numbers as the argument") | |
def area_circle(radius): | |
try: | |
print(3.142 * radius**2) | |
except TypeError: | |
print("area_circle only takes numbers as the argument") | |
def area_rectangle(length, breadth): | |
try: | |
print(length * breadth) | |
except TypeError: | |
print("area_rectangle only takes numbers as the argument") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment