Skip to content

Instantly share code, notes, and snippets.

@santiago-puch-giner
Created May 28, 2017 16:33
Show Gist options
  • Save santiago-puch-giner/8ffd495725a66eb12cb9967d677d3afe to your computer and use it in GitHub Desktop.
Save santiago-puch-giner/8ffd495725a66eb12cb9967d677d3afe to your computer and use it in GitHub Desktop.
Function decorator in Python
import time
""" FUNCTION DECORATOR """
def log_function(time_it=False):
def decorate(func):
def wrapper(*args, **kwargs):
print('LOGGING :: Start function {}'.format(func.__name__))
if time_it:
start_time = time.time()
res = func(*args, **kwargs)
print('LOGGING :: End function {}'.format(func.__name__))
if time_it:
time_spent = time.time() - start_time
print('LOGGING :: Exec time: {:.4f} s'.format(time_spent))
print()
return res
return wrapper
return decorate
""" 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