def uppercase_decorator(func):
def function_wrapper(x):
print("Before calling " + func.__name__)
# function that is decorated making name parameter always uppercase
func(x.upper())
print("After calling " + func.__name__)
return function_wrapper
@uppercase_decorator
def user(name):
print(f"Hi, {name}")
user("Sam")
# output
# Before calling user
# Hi, SAM
# After calling user
# Decorator with arguments
import functools
# First function takes the wanted number of repetition
def repeat(num_times):
# Second function takes the function
def decorator_repeat(func):
# Third function, the wrapper executes the function the number of times wanted
# functools decorator to print the true name of the function passed instead of "wrapper"
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(num_times):
result= func(*args, **kwargs)
return result
return wrapper
return decorator_repeat
# Our function using the decorator
@repeat(num_times= 3)
def greet(name):
print(f"Hello {name}")
greet("thomas")
from functools import wraps
def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logit
def addition_func(x):
"""Do some math."""
return x + x
result = addition_func(4)
# Output: addition_func was called
def deco(function):
def wrap(num):
if num % 2 == 0:
print(num,"is even ")
else:
print(num,"is odd")
function(num)
return wrap
@deco
def display(num):
return num
display(9) # pass any number to check whether number is even or odd
# class decorator
import random
# changes the properties of a function to a class instance
class Eliphant:
def __init__(self,funct):
self._funct = funct
#all return values are storredin momory
self._memory = []
def __call__(self):
returnvalue = self._funct()
self._memory.append(returnvalue)
return returnvalue
def memory(self):
return self._memory
@Eliphant
def random_odd():
return random.choice([1,3,5,7,9])
print(random_odd())
print(random_odd.memory())
print(random_odd())
print(random_odd.memory())
from functools import wraps
def logit(logfile='out.log'):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# Open the logfile and append
with open(logfile, 'a') as opened_file:
# Now we log to the specified logfile
opened_file.write(log_string + '
')
return func(*args, **kwargs)
return wrapped_function
return logging_decorator
@logit()
def myfunc1():
pass
myfunc1()
# Output: myfunc1 was called
# A file called out.log now exists, with the above string
@logit(logfile='func2.log')
def myfunc2():
pass
myfunc2()
# Output: myfunc2 was called
# A file called func2.log now exists, with the above string