Free Python Course | Programming Tutorials
599 subscribers
9 photos
2 files
6 links
Join Noob to Pro in Python in 100 Days! πŸš€ Learn Python with daily lessons, practical examples, free code samples, exercises, and homework. Ideal for beginners and those looking to advance their skills. Start your journey to becoming a Python pro! 🐍
Download Telegram
Day 16: Decorators - Introduction and Use Cases
Welcome to Day 16! Today, we’ll dive into decorators, one of Python’s most powerful and useful features. By the end of this lesson, you will understand how decorators work, when to use them, and how they can improve your code.
πŸ‘1
What is a Decorator?
A decorator in Python is a function that takes another function as an argument, adds some functionality to it, and returns it, without modifying the original function’s structure.

Why Use Decorators?
Code Reusability: You can reuse the same code across multiple functions by applying the same decorator.
Separation of Concerns: Decorators allow you to separate different functionalities like logging, access control, etc.
Clean Code: By using decorators, you avoid cluttering the core functionality of your functions with extra responsibilities.
πŸ‘1
Basic Structure of a Decorator
A decorator wraps around a function to extend or alter its behavior. Here's the basic structure of a decorator.

Example: Basic Decorator
def my_decorator(func):
def wrapper():
print("Something before the function runs.")
func()
print("Something after the function runs.")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()

Explanation:
my_decorator is the decorator function.
@my_decorator is the syntax to apply the decorator to the say_hello() function.
When you call say_hello(), the decorator adds functionality before and after it.

Output:
Something before the function runs.
Hello!
Something after the function runs.
Decorators with Arguments
Sometimes, the function being decorated accepts arguments. To handle this, we modify the decorator to accept any number of arguments using *args and **kwargs.

Example: Decorator with Arguments
def my_decorator(func):
def wrapper(*args, **kwargs):
print(f"Function called with arguments: {args}, {kwargs}")
return func(*args, **kwargs)
return wrapper

@my_decorator
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25)


Output:
Function called with arguments: ('Alice', 25), {}
Hello Alice, you are 25 years old.
πŸ‘1
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.
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
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: 30

This 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
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
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
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.
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.
πŸ‘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 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:

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 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
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 map() Function

What 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 Numbers
def 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
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 Numbers
def 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
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 List
from 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
Creating 100 days perfect plan that's why didn't post anything todayπŸ™‚
❀6πŸ‘5πŸ”₯1
pythoncourse.pdf
433.5 KB
πŸ”₯4❀1