The basic syntax for list comprehension includes three things,
new_list = [expression for item in list]
# an example of using it to convert values of a dice to integers
rolled_dice = [int(i) for i in rolled_dice]
The only difference from list comprehension and using a for loop to use an expression to create a list is its speed and elegance for doing the same thing.
# an example of using list comprehension to square the elements in a given list of integers
squared_list = [pow(i,2) for i in list]
A decorator wraps a function which modifies its behavior.
The way that decorators work is you have 4 pieces:
Some common use cases for a decorator is when you want to activate a function based on the user being logged in or not, to time a function, debugging code and registering plugins.
# an example of decorators being used to check if a user is logged in
def login_required(func):
def wrapper(request, *args, **kwargs):
if not request.user.is_authenticated:
return redirect('login')
return func(request, *args, **kwargs)
return wrapper
@login_required # this is the same as doing restricted_view = login_required(restricted_view)
def restricted_view(request):
# do something if user is authenticated
References