Real-World Use Cases for Decorators
Decorators are extremely useful in a variety of scenarios:
Logging: Track when functions are called and with what parameters.
Timing Functions: Measure how long a function takes to execute.
Authentication and Access Control: Ensure that users have permission to execute certain functions.
Memoization: Cache the results of expensive functions to avoid redundant calculations.
Decorators are extremely useful in a variety of scenarios:
Logging: Track when functions are called and with what parameters.
Timing Functions: Measure how long a function takes to execute.
Authentication and Access Control: Ensure that users have permission to execute certain functions.
Memoization: Cache the results of expensive functions to avoid redundant calculations.
Use Case: Logging with Decorators
A common use of decorators is to log information about when and how a function is used.
Example: Logging Decorator
Output:
This decorator logs the function name and its arguments before calling the function.
A common use of decorators is to log information about when and how a function is used.
Example: Logging Decorator
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling function '{func.__name__}' with arguments {args} and {kwargs}")
return func(*args, **kwargs)
return wrapper
@log_decorator
def add(a, b):
return a + b
result = add(10, 20)
print(f"Result: {result}")
Output:
Calling function 'add' with arguments (10, 20) and {}
Result: 30This decorator logs the function name and its arguments before calling the function.
👍1
Use Case: Timing with Decorators
Another practical use of decorators is to measure how long a function takes to execute.
Example: Timing Decorator
Output:
In this example, the decorator calculates the time taken for the function to execute and prints it.
Another practical use of decorators is to measure how long a function takes to execute.
Example: Timing Decorator
import time
def time_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds")
return result
return wrapper
@time_decorator
def long_running_function():
time.sleep(2)
print("Function completed.")
long_running_function()
Output:
Function completed.
Function 'long_running_function' executed in 2.0002 seconds
In this example, the decorator calculates the time taken for the function to execute and prints it.
👍1
Use Case: Access Control with Decorators
Decorators can be used to restrict access to certain functions based on conditions like user authentication.
Example: Authentication Decorator
In this case, the decorator checks whether the user is authenticated before allowing access to the
Decorators can be used to restrict access to certain functions based on conditions like user authentication.
Example: Authentication Decorator
def requires_authentication(func):
def wrapper(user):
if user.get('authenticated'):
return func(user)
else:
print("Access Denied: User not authenticated.")
return wrapper
@requires_authentication
def view_dashboard(user):
print(f"Welcome, {user['name']}!")
user1 = {'name': 'Alice', 'authenticated': True}
user2 = {'name': 'Bob', 'authenticated': False}
view_dashboard(user1) # Welcome, Alice!
view_dashboard(user2) # Access Denied: User not authenticated.
In this case, the decorator checks whether the user is authenticated before allowing access to the
view_dashboard() function.👍1
Combining Multiple Decorators
You can apply multiple decorators to the same function. When multiple decorators are applied, they are executed from the bottom to the top (closest to the function first).
Example: Multiple Decorators
Output:
You can apply multiple decorators to the same function. When multiple decorators are applied, they are executed from the bottom to the top (closest to the function first).
Example: Multiple Decorators
def decorator_one(func):
def wrapper():
print("Decorator One")
return func()
return wrapper
def decorator_two(func):
def wrapper():
print("Decorator Two")
return func()
return wrapper
@decorator_one
@decorator_two
def greet():
print("Hello!")
greet()
Output:
Decorator One
Decorator Two
Hello!
👍1🥰1
Practice Exercises for Day 16
Exercise 1: Simple Logging Decorator
Create a decorator that logs the execution of a function, including its name and the arguments passed.
Exercise 2: Timing Function
Write a decorator that times how long a function takes to execute and prints the execution time.
Exercise 3: Simple Authentication
Write a decorator that checks if a user is authenticated. If not, it should print "Access denied."
Exercise 4: Memoization Decorator
Write a decorator that caches the results of a function. If the function is called with the same arguments again, return the cached result instead of recomputing it.
Exercise 1: Simple Logging Decorator
Create a decorator that logs the execution of a function, including its name and the arguments passed.
Exercise 2: Timing Function
Write a decorator that times how long a function takes to execute and prints the execution time.
Exercise 3: Simple Authentication
Write a decorator that checks if a user is authenticated. If not, it should print "Access denied."
Exercise 4: Memoization Decorator
Write a decorator that caches the results of a function. If the function is called with the same arguments again, return the cached result instead of recomputing it.
Summary
In Day 16, we learned:
What a decorator is and how it can modify or extend the behavior of functions.
How to create a decorator, including passing arguments to both the decorator and the decorated function.
Common use cases for decorators, such as logging, timing, and access control.
How to apply multiple decorators to a function.
Decorators are a powerful feature in Python that help maintain clean and modular code. They allow you to extend the behavior of your functions while keeping them easy to read and manage.
In Day 16, we learned:
What a decorator is and how it can modify or extend the behavior of functions.
How to create a decorator, including passing arguments to both the decorator and the decorated function.
Common use cases for decorators, such as logging, timing, and access control.
How to apply multiple decorators to a function.
Decorators are a powerful feature in Python that help maintain clean and modular code. They allow you to extend the behavior of your functions while keeping them easy to read and manage.
👍2🔥2
Day 17: Python Built-in Functions (zip(), enumerate(), and More)
Welcome to Day 17! Today, we will explore some of Python's most useful built-in functions. These functions are incredibly powerful and can help you write more efficient and readable code. Specifically, we’ll focus on functions like
Welcome to Day 17! Today, we will explore some of Python's most useful built-in functions. These functions are incredibly powerful and can help you write more efficient and readable code. Specifically, we’ll focus on functions like
zip(), enumerate(), map(), filter(), and reduce().👍3
Python Built-in Functions Overview
Python comes with a rich set of built-in functions that can perform various operations without requiring any import of additional modules. Some of the common built-in functions we will cover today include:
Python comes with a rich set of built-in functions that can perform various operations without requiring any import of additional modules. Some of the common built-in functions we will cover today include:
zip(): Combines elements from multiple iterables.enumerate(): Adds a counter to an iterable.map(): Applies a function to every item of an iterable.filter(): Filters elements based on a condition.reduce(): Aggregates items in an iterable by applying a function cumulatively.The zip() Function
What is zip()?
The
Syntax
Example: Using
Output:
In this example,
Example: Looping with
Output:
Here,
What is zip()?
The
zip() function takes multiple iterables (e.g., lists, tuples) and returns an iterator of tuples, where each tuple contains one element from each iterable. It is often used when you need to process multiple sequences in parallel.Syntax
zip(*iterables)
Example: Using
zip()list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)
print(list(zipped)) # Convert the zip object to a list
Output:
[(1, 'a'), (2, 'b'), (3, 'c')]
In this example,
zip() combines elements from list1 and list2 into tuples.Example: Looping with
zip()names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Output:
Alice: 85
Bob: 90
Charlie: 78
Here,
zip() pairs elements from the two lists so we can process them together.👍2
The enumerate() Function
What is
The
Syntax
Example: Using
Output:
In this example,
Example: Custom Start Value with
Output:
You can set the starting index using the
What is
enumerate()?The
enumerate() function adds a counter to an iterable and returns it as an enumerate object. This is useful when you need both the index and the value of elements in an iterable during iteration.Syntax
enumerate(iterable, start=0)
Example: Using
enumerate()fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Output:
0: apple
1: banana
2: cherry
In this example,
enumerate() allows us to easily keep track of the index of each fruit.Example: Custom Start Value with
enumerate()fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}")
Output:
1: apple
2: banana
3: cherry
You can set the starting index using the
start parameter.The
What is
The
Syntax
Example: Using
Output:
In this example, the
Example: Using
Output:
You can use a
map() FunctionWhat is
map()?The
map() function applies a given function to all items in an input iterable (like a list) and returns an iterator. This is useful for transforming the elements of an iterable in a single line.Syntax
map(function, iterable, ...)
Example: Using
map() to Square Numbersdef square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # Convert the map object to a list
Output:
[1, 4, 9, 16, 25]
In this example, the
map() function applies the square() function to each element of the numbers list.Example: Using
lambda with map()numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))
Output:
[1, 4, 9, 16, 25]
You can use a
lambda function to achieve the same result in a more concise way.The filter() Function
What is
The
Syntax:
Example: Using
Output:
In this example, the
Example: Using
Output:
Again, using a
What is
filter()?The
filter() function filters elements from an iterable based on a condition defined by a function. It returns only the elements for which the function returns True.Syntax:
filter(function, iterable)
Example: Using
filter() to Filter Even Numbersdef is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # Convert the filter object to a list
Output:
[2, 4, 6]
In this example, the
filter() function keeps only the even numbers from the list.Example: Using
lambda with filter()numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
Output:
[2, 4, 6]
Again, using a
lambda function simplifies the code.The reduce() Function
What is r
The
Syntax
To use
Example: Using
Output:
In this example,
Example: Using
Output:
Using
What is r
educe()?The
reduce() function from the functools module applies a function cumulatively to the items of an iterable, reducing the iterable to a single value.Syntax
reduce(function, iterable)
To use
reduce(), you need to import it from the functools module.Example: Using
reduce() to Sum a Listfrom functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
total_sum = reduce(add, numbers)
print(total_sum)
Output:
15
In this example,
reduce() adds each number in the list to the next, resulting in the sum of all numbers.Example: Using
lambda with reduce()from functools import reduce
numbers = [1, 2, 3, 4, 5]
total_sum = reduce(lambda x, y: x + y, numbers)
print(total_sum)
Output:
15
Using
lambda with reduce() simplifies the function definition.👍3❤1
New users check pinned message 📌
👍6
Are you dead?
👎27👨💻11👍8❤6😁5💯2🗿2🤗1
If you are alive the comment your name👇
👍27❤13🔥3