Created
December 7, 2024 16:20
-
-
Save tinshade/9e14adf052f1cacec75a354da10eb470 to your computer and use it in GitHub Desktop.
Example of how to use a decorator in Python
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
| from functools import wraps | |
| import json | |
| import os | |
| def read_from_json_file(json_file_path:str): | |
| def decorator(func): | |
| @wraps(func) | |
| def wrapper(*args, **kwargs): | |
| data = None | |
| if not os.path.isfile(json_file_path): | |
| return func(*args, **kwargs, data=data) | |
| with open(json_file_path, 'r') as file: | |
| data = json.load(file) | |
| return func(*args, **kwargs, data=data) | |
| return wrapper | |
| return decorator | |
| class Testing: | |
| FILEPATH = './test.json' | |
| @read_from_json_file(json_file_path=FILEPATH) | |
| def generate_data(self, data): | |
| print(data) | |
| t = Testing() | |
| t.generate_data() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment