Created
February 3, 2024 07:22
-
-
Save aperezlillo/ab14edca9901abb027f87d649b9fdcfd to your computer and use it in GitHub Desktop.
Python decorators
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 timing_decorator(func): | |
| import time | |
| def wrapper(*args, **kwargs): | |
| start = time.time() | |
| result = func(*args, **kwargs) | |
| end = time.time() | |
| print(f"{func.__name__} took {end - start} seconds to run.") | |
| return result | |
| return wrapper | |
| def debug_decorator(func): | |
| def wrapper(*args, **kwargs): | |
| print(f"Function {func.__name__} called with {args} and {kwargs}") | |
| result = func(*args, **kwargs) | |
| print(f"{func.__name__} returned {result}") | |
| return result | |
| return wrapper | |
| def memoize_decorator(func): | |
| # recursive functions memory | |
| memo = {} | |
| def wrapper(*args): | |
| if args in memo: | |
| return memo[args] | |
| result = func(*args) | |
| memo[args] = result | |
| return result | |
| return wrapper | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment