Skip to content

Instantly share code, notes, and snippets.

@tinshade
Created December 7, 2024 16:20
Show Gist options
  • Select an option

  • Save tinshade/9e14adf052f1cacec75a354da10eb470 to your computer and use it in GitHub Desktop.

Select an option

Save tinshade/9e14adf052f1cacec75a354da10eb470 to your computer and use it in GitHub Desktop.
Example of how to use a decorator in Python
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