my_new_list = [ expression for item in list ]
expression
inside the square brackets
multiples_of_three = [x*3 for x in range(10)]
item
inside the square bracketslist
inside the square brackets.Uses @
symbol as syntactic sugar, referred to a pie syntax to show the decorator function and pass it to the function below
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_whee():
print("Whee!")
@my_decorator
is the same as setting say_whee = my_decorator(say_whee)
*args and **kwargs
def do_twice(func):
def wrapper_do_twice(*args, **kwargs):
func(*args, **kwargs)
return func(*args, **kwargs) # wrapper function needs to return the return value of the decorated function
return wrapper_do_twice
@do_twice
def return_greeting(name):
print("Creating greeting")
return f"Hi {name}"
return_greeting("Adam")
# Creating greeting
# Creating greeting
# 'Hi Adam'