Skip to content

Instantly share code, notes, and snippets.

@santiago-puch-giner
Created May 28, 2017 16:27
Show Gist options
  • Save santiago-puch-giner/00505b65db1340158b86690a2e2472e1 to your computer and use it in GitHub Desktop.
Save santiago-puch-giner/00505b65db1340158b86690a2e2472e1 to your computer and use it in GitHub Desktop.
Class-based Python decorators
import time
""" EXAMPLE LOGGING DECORATOR """
class log_function(object):
def __init__(self, time_it=False):
self.time_it = time_it
def __call__(self, func, *args, **kwargs):
def wrapper(*args, **kwargs):
print('LOGGING :: Start function {}'.format(func.__name__))
if self.time_it:
start_time = time.time()
res = func(*args, **kwargs)
print('LOGGING :: End function {}'.format(func.__name__))
if self.time_it:
time_spent = time.time() - start_time
print('LOGGING :: Exec time: {:.4f} s'.format(time_spent))
print()
return res
return wrapper
""" DECORATED EXAMPLE FUNCTIONS """
@log_function()
def greet_default(name, surname):
print('Good morning {} {}!'.format(name, surname))
# Another greet function, timing included
@log_function(time_it=True)
def greet_timing(name):
print('Good morning {}!'.format(name))
# Simulate execution time to observe the timing log
time.sleep(1)
""" MAIN """
if __name__ == '__main__':
greet_default('John', 'Doe')
# LOGGING :: Start function greet_default
# Good morning John Doe!
# LOGGING :: End function greet_default
greet_default(surname='John', name='Doe')
# LOGGING :: Start function greet_default
# Good morning Doe John!
# LOGGING :: End function greet_default
greet_timing('James')
# LOGGING :: Start function greet_timing
# Good morning James!
# LOGGING :: End function greet_timing
# LOGGING :: Exec time: 1.0014 s
greet_timing(name='James')
# LOGGING :: Start function greet_timing
# Good morning James!
# LOGGING :: End function greet_timing
# LOGGING :: Exec time: 1.0004 s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment