Python coding
๐ Python Tip #49: The datetime Module Working with dates and times is a common task in Python. The datetime module allows you to create, manipulate, and format dates and times with ease. --- Importing datetime from datetime import datetime --- Gettingโฆ
๐ Python Tip #50: The
The
It makes it easy to perform date and time arithmetic.
---
Importing
---
Adding Days
Output:
(The output depends on the current date and time.)
---
Subtracting Days
This returns the date 30 days before today.
---
Adding Hours and Minutes
This calculates the date and time 2 hours and 30 minutes from now.
---
Finding the Difference Between Dates
Output:
The result is a
---
Why use
โ Easily add or subtract dates and times
โ Calculate the difference between two dates
โ Supports days, hours, minutes, seconds, and weeks
โ Commonly used in scheduling, reminders, logging, and automation
---
Challenge:
Create a program that:
1. Gets today's date.
2. Calculates the date 100 days from today.
3. Prints both dates.
4. Displays the number of days between them.
datetime.timedelta ClassThe
timedelta class from Python's datetime module represents a duration or difference between two dates or times.It makes it easy to perform date and time arithmetic.
---
Importing
timedeltafrom datetime import datetime, timedelta
---
Adding Days
from datetime import datetime, timedelta
today = datetime.now()
future = today + timedelta(days=7)
print(future)
Output:
2026-07-15 14:30:15.123456
(The output depends on the current date and time.)
---
Subtracting Days
from datetime import datetime, timedelta
today = datetime.now()
past = today - timedelta(days=30)
print(past)
This returns the date 30 days before today.
---
Adding Hours and Minutes
from datetime import datetime, timedelta
now = datetime.now()
later = now + timedelta(hours=2, minutes=30)
print(later)
This calculates the date and time 2 hours and 30 minutes from now.
---
Finding the Difference Between Dates
from datetime import datetime
date1 = datetime(2026, 7, 1)
date2 = datetime(2026, 7, 15)
difference = date2 - date1
print(difference)
print(difference.days)
Output:
14 days, 0:00:00
14
The result is a
timedelta object representing the time difference.---
Why use
timedelta?โ Easily add or subtract dates and times
โ Calculate the difference between two dates
โ Supports days, hours, minutes, seconds, and weeks
โ Commonly used in scheduling, reminders, logging, and automation
---
Challenge:
Create a program that:
1. Gets today's date.
2. Calculates the date 100 days from today.
3. Prints both dates.
4. Displays the number of days between them.
Python coding
๐ Python Tip #50: The datetime.timedelta Class The timedelta class from Python's datetime module represents a duration or difference between two dates or times. It makes it easy to perform date and time arithmetic. --- Importing timedelta from datetimeโฆ
๐ก Python Tip #51: The
The
UUIDs are commonly used to create unique IDs for users, orders, files, API keys, and database records.
---
Importing
---
Generating a Random UUID
Example Output:
Your output will be different every time because each UUID is randomly generated.
---
Converting a UUID to a String
Output:
This is useful when storing UUIDs in databases or sending them through APIs.
---
Generating Multiple UUIDs
Example Output:
Each generated UUID is unique.
---
Using UUIDs as Dictionary Keys
Output:
---
Why use
โ Generates globally unique identifiers
โ Prevents ID collisions
โ No need for auto-incrementing numbers
โ Commonly used in web development, databases, distributed systems, and REST APIs
---
Challenge:
Create a program that:
1. Generates 5 random UUIDs.
2. Stores them in a list.
3. Prints each UUID on a separate line.
4. Verifies that all generated UUIDs are unique.
uuid ModuleThe
uuid module generates Universally Unique Identifiers (UUIDs).UUIDs are commonly used to create unique IDs for users, orders, files, API keys, and database records.
---
Importing
uuidimport uuid
---
Generating a Random UUID
import uuid
unique_id = uuid.uuid4()
print(unique_id)
Example Output:
550e8400-e29b-41d4-a716-446655440000
Your output will be different every time because each UUID is randomly generated.
---
Converting a UUID to a String
import uuid
unique_id = uuid.uuid4()
print(str(unique_id))
Output:
550e8400-e29b-41d4-a716-446655440000
This is useful when storing UUIDs in databases or sending them through APIs.
---
Generating Multiple UUIDs
import uuid
for _ in range(3):
print(uuid.uuid4())
Example Output:
9b1deb4d-3b7d-4f47-bc2b-4e7f5f36c91e
b87d6b11-5c61-4e2a-a93e-91b7ef9d82a3
7db3d59f-0ec4-4b5e-8f5f-cd28bca1e75f
Each generated UUID is unique.
---
Using UUIDs as Dictionary Keys
import uuid
users = {}
user_id = uuid.uuid4()
users[user_id] = "Yehya"
print(users)
Output:
{
UUID('550e8400-e29b-41d4-a716-446655440000'): 'Yehya'
}---
Why use
uuid?โ Generates globally unique identifiers
โ Prevents ID collisions
โ No need for auto-incrementing numbers
โ Commonly used in web development, databases, distributed systems, and REST APIs
---
Challenge:
Create a program that:
1. Generates 5 random UUIDs.
2. Stores them in a list.
3. Prints each UUID on a separate line.
4. Verifies that all generated UUIDs are unique.
Python coding
๐ก Python Tip #51: The uuid Module The uuid module generates Universally Unique Identifiers (UUIDs). UUIDs are commonly used to create unique IDs for users, orders, files, API keys, and database records. --- Importing uuid import uuid --- Generating aโฆ
๐ Python Tip #52: The
The
Enums make your code more readable, safer, and easier to maintain.
---
Importing
---
Creating an Enum
Output:
---
Accessing the Name and Value
Output:
---
Comparing Enum Members
Output:
Enums should be compared with other enum members, not with integers.
---
Looping Through an Enum
Output:
---
Why use
โ Makes code more readable
โ Replaces "magic numbers" with meaningful names
โ Prevents invalid constant values
โ Commonly used for application states, user roles, HTTP status codes, and configuration options
---
Challenge:
Create an enum named:
with the following members:
Then:
1. Print the name and value of
2. Loop through all members and print their names and values.
enum.Enum ClassThe
Enum class from Python's enum module allows you to create a set of named constant values.Enums make your code more readable, safer, and easier to maintain.
---
Importing
Enumfrom enum import Enum
---
Creating an Enum
from enum import Enum
class Status(Enum):
PENDING = 1
RUNNING = 2
COMPLETED = 3
print(Status.PENDING)
Output:
Status.PENDING
---
Accessing the Name and Value
from enum import Enum
class Status(Enum):
PENDING = 1
RUNNING = 2
COMPLETED = 3
print(Status.RUNNING.name)
print(Status.RUNNING.value)
Output:
RUNNING
2
---
Comparing Enum Members
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
if Color.RED == Color.RED:
print("They are equal.")
Output:
They are equal.
Enums should be compared with other enum members, not with integers.
---
Looping Through an Enum
from enum import Enum
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
for day in Day:
print(day.name, day.value)
Output:
MONDAY 1
TUESDAY 2
WEDNESDAY 3
---
Why use
Enum?โ Makes code more readable
โ Replaces "magic numbers" with meaningful names
โ Prevents invalid constant values
โ Commonly used for application states, user roles, HTTP status codes, and configuration options
---
Challenge:
Create an enum named:
TrafficLight
with the following members:
RED = 1
YELLOW = 2
GREEN = 3
Then:
1. Print the name and value of
GREEN.2. Loop through all members and print their names and values.
Python coding
๐ Python Tip #52: The enum.Enum Class The Enum class from Python's enum module allows you to create a set of named constant values. Enums make your code more readable, safer, and easier to maintain. --- Importing Enum from enum import Enum --- Creatingโฆ
๐ Python Tip #53: The
The
Unlike the
---
Importing
---
Generating a Secure Random Number
Output:
The output will be a secure random integer between
---
Choosing a Random Item
Output:
A random item is selected securely.
---
Generating a Secure Token
Example Output:
This creates a secure hexadecimal token with 16 random bytes.
---
Generating a Strong Password
Example Output:
A different password will be generated each time.
---
Why use
โ Generates cryptographically secure random values
โ More secure than the
โ Ideal for passwords, API keys, authentication tokens, and session IDs
โ Recommended for security-related applications
---
Challenge:
Create a program that:
1. Generates a secure password with 16 characters.
2. The password should contain:
- Uppercase letters
- Lowercase letters
- Numbers
- Special characters
3. Print the generated password.
secrets ModuleThe
secrets module is designed for generating cryptographically secure random numbers, tokens, and passwords.Unlike the
random module, secrets should be used for security-related tasks.---
Importing
secretsimport secrets
---
Generating a Secure Random Number
import secrets
number = secrets.randbelow(100)
print(number)
Output:
42
The output will be a secure random integer between
0 and 99.---
Choosing a Random Item
import secrets
colors = ["Red", "Green", "Blue", "Black"]
choice = secrets.choice(colors)
print(choice)
Output:
Green
A random item is selected securely.
---
Generating a Secure Token
import secrets
token = secrets.token_hex(16)
print(token)
Example Output:
9f8d7c2b1a4e5f6d8c9b0a1d2e3f4a5b
This creates a secure hexadecimal token with 16 random bytes.
---
Generating a Strong Password
import secrets
import string
characters = string.ascii_letters + string.digits + string.punctuation
password = "".join(
secrets.choice(characters)
for _ in range(12)
)
print(password)
Example Output:
A#7mP!2xQ9@k
A different password will be generated each time.
---
Why use
secrets?โ Generates cryptographically secure random values
โ More secure than the
random module for sensitive data โ Ideal for passwords, API keys, authentication tokens, and session IDs
โ Recommended for security-related applications
---
Challenge:
Create a program that:
1. Generates a secure password with 16 characters.
2. The password should contain:
- Uppercase letters
- Lowercase letters
- Numbers
- Special characters
3. Print the generated password.
Python coding
๐ Python Tip #53: The secrets Module The secrets module is designed for generating cryptographically secure random numbers, tokens, and passwords. Unlike the random module, secrets should be used for security-related tasks. --- Importing secrets importโฆ
๐ Python Tip #54: The
The
It automatically generates methods such as
---
Importing
---
Creating a Data Class
Output:
Notice that Python automatically created the constructor and the string representation.
---
Accessing Attributes
Output:
---
Comparing Objects
Data classes automatically support equality comparison.
Output:
---
Using Default Values
Output:
If no country is provided,
---
Why use
โ Eliminates repetitive boilerplate code
โ Automatically generates constructors and other useful methods
โ Improves code readability and maintainability
โ Commonly used in APIs, configuration objects, and data models
---
Challenge:
Create a data class named:
with the following fields:
Then:
1. Create two identical
2. Print one of them.
3. Check whether the two objects are equal.
dataclasses ModuleThe
dataclasses module helps you create classes that mainly store data without writing repetitive boilerplate code.It automatically generates methods such as
__init__(), __repr__(), and __eq__().---
Importing
dataclassfrom dataclasses import dataclass
---
Creating a Data Class
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
grade: str
student = Student("Ali", 18, "A")
print(student)
Output:
Student(name='Ali', age=18, grade='A')
Notice that Python automatically created the constructor and the string representation.
---
Accessing Attributes
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
student = Student("Yehya", 16)
print(student.name)
print(student.age)
Output:
Yehya
16
---
Comparing Objects
Data classes automatically support equality comparison.
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages: int
book1 = Book("Python", 300)
book2 = Book("Python", 300)
print(book1 == book2)
Output:
True
---
Using Default Values
from dataclasses import dataclass
@dataclass
class User:
name: str
country: str = "Ethiopia"
user = User("Yehya")
print(user)
Output:
User(name='Yehya', country='Ethiopia')
If no country is provided,
"Ethiopia" is used by default.---
Why use
dataclasses?โ Eliminates repetitive boilerplate code
โ Automatically generates constructors and other useful methods
โ Improves code readability and maintainability
โ Commonly used in APIs, configuration objects, and data models
---
Challenge:
Create a data class named:
Car
with the following fields:
brand
model
year
Then:
1. Create two identical
Car objects.2. Print one of them.
3. Check whether the two objects are equal.
Python coding
๐ Python Tip #54: The dataclasses Module The dataclasses module helps you create classes that mainly store data without writing repetitive boilerplate code. It automatically generates methods such as __init__(), __repr__(), and __eq__(). --- Importingโฆ
๐ก Python Tip #55: The
The
It is the modern replacement for using
---
Importing
---
Creating a Path Object
Output:
---
Checking if a File Exists
Output:
or
```python
False
python
from pathlib import Path
file = Path("report.pdf")
print(file.name)
print(file.stem)
print(file.suffix)
python
report.pdf
report
.pdf
python
from pathlib import Path
folder = Path("Projects")
folder.mkdir(exist_ok=True)
print("Folder created.")
python
from pathlib import Path
folder = Path(".")
for file in folder.iterdir():
print(file)
python
PythonProjects
python
notes.txt
inside that folder.
3. Print:
- The full path
- The file name
- The file extension
pathlib ModuleThe
pathlib module provides an object-oriented way to work with files and directories.It is the modern replacement for using
os.path in Python.---
Importing
Pathfrom pathlib import Path
---
Creating a Path Object
from pathlib import Path
file = Path("example.txt")
print(file)
Output:
example.txt
---
Checking if a File Exists
from pathlib import Path
file = Path("example.txt")
print(file.exists())
Output:
True
or
```python
False
depending on whether the file exists.
---
Getting File Information
python
from pathlib import Path
file = Path("report.pdf")
print(file.name)
print(file.stem)
print(file.suffix)
Output:
python
report.pdf
report
- `name` returns the full filename.
- `stem` returns the filename without the extension.
- `suffix` returns the file extension.
---
Creating a Directory
python
from pathlib import Path
folder = Path("Projects")
folder.mkdir(exist_ok=True)
print("Folder created.")
The `exist_ok=True` argument prevents an error if the folder already exists.
---
Listing Files in a Directory
python
from pathlib import Path
folder = Path(".")
for file in folder.iterdir():
print(file)
This prints every file and folder in the current directory.
---
Why use `pathlib`?
โ Modern and easy-to-read syntax
โ Works across Windows, macOS, and Linux
โ Simplifies file and directory operations
โ Commonly used in automation, scripting, web development, and data science
---
Challenge:
Create a program that:
1. Creates a folder named:
python
PythonProjects
2. Creates a `Path` object for a file named:
python
notes.txt
`inside that folder.
3. Print:
- The full path
- The file name
- The file extension
Python coding
๐ก Python Tip #55: The pathlib Module The pathlib module provides an object-oriented way to work with files and directories. It is the modern replacement for using os.path in Python. --- Importing Path from pathlib import Path --- Creating a Path Objectโฆ
๐ Python Tip #56: The
The
Unlike
---
Importing
---
Basic Logging
Output:
---
Logging Levels
Python provides several logging levels.
Output:
---
Logging to a File
Instead of displaying messages in the terminal, you can save them to a file.
A file named
---
Formatting Log Messages
Example Output:
---
Why use
โ Better than using
โ Supports different log levels
โ Can save logs to files automatically
โ Essential for professional applications, APIs, and server programs
---
Challenge:
Create a program that:
1. Configures logging to save messages to a file named:
2. Logs the following messages:
3. Open the log file and verify that all three messages were saved.
logging ModuleThe
logging module provides a flexible way to record messages while your program is running.Unlike
print(), logging allows you to categorize messages by importance and save them to files.---
Importing
loggingimport logging
---
Basic Logging
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started.")
Output:
INFO:root:Program started.
---
Logging Levels
Python provides several logging levels.
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Debug message")
logging.info("Information message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical error")
Output:
DEBUG:root:Debug message
INFO:root:Information message
WARNING:root:Warning message
ERROR:root:Error message
CRITICAL:root:Critical error
---
Logging to a File
Instead of displaying messages in the terminal, you can save them to a file.
import logging
logging.basicConfig(
filename="app.log",
level=logging.INFO
)
logging.info("Application started.")
logging.warning("Low disk space.")
A file named
app.log will be created containing the log messages.---
Formatting Log Messages
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("User logged in.")
Example Output:
2026-07-22 10:15:30 - INFO - User logged in.
---
Why use
logging?โ Better than using
print() for debugging โ Supports different log levels
โ Can save logs to files automatically
โ Essential for professional applications, APIs, and server programs
---
Challenge:
Create a program that:
1. Configures logging to save messages to a file named:
program.log
2. Logs the following messages:
INFO: Program started
WARNING: Low memory
ERROR: File not found
3. Open the log file and verify that all three messages were saved.
Python coding
๐ Python Tip #56: The logging Module The logging module provides a flexible way to record messages while your program is running. Unlike print(), logging allows you to categorize messages by importance and save them to files. --- Importing logging importโฆ
๐ Python Tip #57: The
The
It is commonly used to build professional command-line applications and automation scripts.
---
Importing
---
Basic Example
Running the program:
Output:
---
Adding Optional Arguments
Optional arguments start with
Run:
```bash
python app.py --age 16
python
16
python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--country", default="Ethiopia")
args = parser.parse_args()
print(args.country)
bash
python app.py
python
Ethiopia
python
import argparse
parser = argparse.ArgumentParser(
description="Simple Calculator"
)
parser.add_argument("--num", type=int)
parser.parse_args()
bash
python app.py --help
text
usage: app.py [-h] [--num NUM]
Simple Calculator
options:
-h, --help Show this help message and exit
--num NUM Enter a number
text
--name
--age
--country
text
Name: Yehya
Age: 16
Country: Ethiopia
If `--country` is not provided, use `"Unknown"` as the default value.
argparse ModuleThe
argparse module allows your Python programs to accept command-line arguments.It is commonly used to build professional command-line applications and automation scripts.
---
Importing
argparseimport argparse
---
Basic Example
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
print(f"Hello, {args.name}!")
Running the program:
python app.py Yehya
Output:
Hello, Yehya!
---
Adding Optional Arguments
Optional arguments start with
--.import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--age", type=int)
args = parser.parse_args()
print(args.age)
Run:
```bash
python app.py --age 16
Output:
python
16
---
Providing Default Values
python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--country", default="Ethiopia")
args = parser.parse_args()
print(args.country)
Run:
bash
python app.py
Output:
python
Ethiopia
---
Displaying Help
`argparse` automatically generates a help message.
python
import argparse
parser = argparse.ArgumentParser(
description="Simple Calculator"
)
parser.add_argument("--num", type=int)
parser.parse_args()
Run:
bash
python app.py --help
Example Output:
text
usage: app.py [-h] [--num NUM]
Simple Calculator
options:
-h, --help Show this help message and exit
--num NUM Enter a number
---
Why use `argparse`?
โ Makes command-line programs easy to use
โ Automatically validates user input
โ Generates built-in help messages
โ Widely used in automation, DevOps, and professional Python tools
---
Challenge:
Create a program that accepts the following command-line arguments:
text
--name
--age
--country
Then print the information in this format:
text
Name: Yehya
Age: 16
Country: Ethiopia
`If `--country` is not provided, use `"Unknown"` as the default value.
Python coding
๐ Python Tip #57: The argparse Module The argparse module allows your Python programs to accept command-line arguments. It is commonly used to build professional command-line applications and automation scripts. --- Importing argparse import argparseโฆ
๐ Python Tip #58: The
The
It is useful for testing, data processing, and handling temporary data.
---
Importing
---
Creating a Temporary File
Output:
The file is automatically deleted after the
---
Creating a Temporary Directory
Example Output:
The directory is automatically removed when you're done.
---
Creating a Named Temporary File
Output:
Unlike
---
Getting the File Name
Example Output:
The exact path depends on your operating system.
---
Why use
โ Automatically cleans up temporary files and folders
โ Prevents clutter on your system
โ Securely creates temporary storage
โ Commonly used in testing, file processing, and automation
---
Challenge:
Create a program that:
1. Creates a temporary file.
2. Writes the text:
3. Reads the contents back and prints them.
4. Lets Python automatically delete the file when the program finishes.
tempfile ModuleThe
tempfile module allows you to create temporary files and directories that are automatically cleaned up when no longer needed.It is useful for testing, data processing, and handling temporary data.
---
Importing
tempfileimport tempfile
---
Creating a Temporary File
import tempfile
with tempfile.TemporaryFile() as file:
file.write(b"Hello, Python!")
file.seek(0)
print(file.read())
Output:
b'Hello, Python!'
The file is automatically deleted after the
with block ends.---
Creating a Temporary Directory
import tempfile
with tempfile.TemporaryDirectory() as folder:
print(folder)
Example Output:
C:\Users\User\AppData\Local\Temp\tmpabc123
The directory is automatically removed when you're done.
---
Creating a Named Temporary File
import tempfile
with tempfile.NamedTemporaryFile(mode="w+", delete=True) as file:
file.write("Temporary data")
file.seek(0)
print(file.read())
Output:
Temporary data
Unlike
TemporaryFile(), a NamedTemporaryFile has a visible filename while it exists.---
Getting the File Name
import tempfile
with tempfile.NamedTemporaryFile() as file:
print(file.name)
Example Output:
C:\Users\User\AppData\Local\Temp\tmpx9z4ab.tmp
The exact path depends on your operating system.
---
Why use
tempfile?โ Automatically cleans up temporary files and folders
โ Prevents clutter on your system
โ Securely creates temporary storage
โ Commonly used in testing, file processing, and automation
---
Challenge:
Create a program that:
1. Creates a temporary file.
2. Writes the text:
Learning Python is fun!
3. Reads the contents back and prints them.
4. Lets Python automatically delete the file when the program finishes.
Python coding
๐ Python Tip #58: The tempfile Module The tempfile module allows you to create temporary files and directories that are automatically cleaned up when no longer needed. It is useful for testing, data processing, and handling temporary data. --- Importingโฆ
๐ก Python Tip #59: The
The
It makes it easy to copy, move, rename, and delete files and folders.
---
Importing
---
Copying a File
This creates a copy of
---
Moving or Renaming a File
If the destination is in another folder, the file is moved. If it's in the same folder with a different name, it is renamed.
---
Copying an Entire Directory
This copies the entire
---
Deleting a Directory
Warning:
---
Getting Disk Usage
Example Output:
---
Why use
โ Copy, move, and rename files easily
โ Copy or remove entire directories
โ Check disk usage information
โ Commonly used in backup tools, automation scripts, and file management applications
---
Challenge:
Create a program that:
1. Creates a copy of a file named:
2. Rename the copied file to:
3. Print a success message after each operation.
shutil ModuleThe
shutil module provides high-level file and directory operations.It makes it easy to copy, move, rename, and delete files and folders.
---
Importing
shutilimport shutil
---
Copying a File
import shutil
shutil.copy("source.txt", "backup.txt")
print("File copied successfully.")
This creates a copy of
source.txt named backup.txt.---
Moving or Renaming a File
import shutil
shutil.move("old_file.txt", "new_file.txt")
print("File moved or renamed.")
If the destination is in another folder, the file is moved. If it's in the same folder with a different name, it is renamed.
---
Copying an Entire Directory
import shutil
shutil.copytree("Project", "Project_Backup")
print("Directory copied.")
This copies the entire
Project folder, including all its files and subfolders.---
Deleting a Directory
import shutil
shutil.rmtree("Old_Project")
print("Directory deleted.")
Warning:
rmtree() permanently deletes the directory and everything inside it.---
Getting Disk Usage
import shutil
usage = shutil.disk_usage(".")
print(f"Total: {usage.total} bytes")
print(f"Used: {usage.used} bytes")
print(f"Free: {usage.free} bytes")
Example Output:
Total: 512110190592 bytes
Used: 301245964288 bytes
Free: 210864226304 bytes
---
Why use
shutil?โ Copy, move, and rename files easily
โ Copy or remove entire directories
โ Check disk usage information
โ Commonly used in backup tools, automation scripts, and file management applications
---
Challenge:
Create a program that:
1. Creates a copy of a file named:
notes.txt
2. Rename the copied file to:
notes_backup.txt
3. Print a success message after each operation.
Python coding
๐ก Python Tip #59: The shutil Module The shutil module provides high-level file and directory operations. It makes it easy to copy, move, rename, and delete files and folders. --- Importing shutil import shutil --- Copying a File import shutil shutโฆ
๐ Python Tip #60: The
The
It helps you manage resources such as files, database connections, and locks safely and cleanly.
---
Importing
---
Creating a Custom Context Manager
Output:
The code before
---
Managing Resources
The file is automatically closed after leaving the
---
Ignoring Exceptions
Use
If the file doesn't exist, the program continues without raising an error.
---
Redirecting Output
You can temporarily redirect printed output.
The text is written to
---
Why use
โ Create custom context managers easily
โ Automatically manage resources
โ Simplify exception handling
โ Commonly used in file handling, testing, logging, and resource management
---
Challenge:
Create a custom context manager that:
1. Prints:
before entering the
2. Prints:
after leaving the
3. Inside the
contextlib ModuleThe
contextlib module provides utilities for working with context managers.It helps you manage resources such as files, database connections, and locks safely and cleanly.
---
Importing
contextmanagerfrom contextlib import contextmanager
---
Creating a Custom Context Manager
from contextlib import contextmanager
@contextmanager
def my_context():
print("Entering context...")
yield
print("Exiting context...")
with my_context():
print("Inside the block")
Output:
Entering context...
Inside the block
Exiting context...
The code before
yield runs when entering the block, and the code after yield runs when exiting it.---
Managing Resources
from contextlib import contextmanager
@contextmanager
def open_file(filename):
file = open(filename, "w")
try:
yield file
finally:
file.close()
with open_file("example.txt") as f:
f.write("Hello, Python!")
The file is automatically closed after leaving the
with block.---
Ignoring Exceptions
Use
suppress() to ignore specific exceptions.from contextlib import suppress
with suppress(FileNotFoundError):
open("missing_file.txt")
If the file doesn't exist, the program continues without raising an error.
---
Redirecting Output
You can temporarily redirect printed output.
from contextlib import redirect_stdout
with open("output.txt", "w") as file:
with redirect_stdout(file):
print("Hello, Python!")
The text is written to
output.txt instead of appearing in the terminal.---
Why use
contextlib?โ Create custom context managers easily
โ Automatically manage resources
โ Simplify exception handling
โ Commonly used in file handling, testing, logging, and resource management
---
Challenge:
Create a custom context manager that:
1. Prints:
Starting task...
before entering the
with block.2. Prints:
Task completed.
after leaving the
with block.3. Inside the
with block, print:Learning Python Context Managers!
Python coding pinned ยซIntroduction to Programming with Python --- What is Python? Python is a popular programming language created by Guido van Rossum in 1991. It is known for: - Simplicity - Readability - Flexibility - Powerful libraries Python is beginner-friendly whileโฆยป
Python coding
๐ Python Tip #60: The contextlib Module The contextlib module provides utilities for working with context managers. It helps you manage resources such as files, database connections, and locks safely and cleanly. --- Importing contextmanager from contextlibโฆ
๐ Python Tip #61: The
The
This is known as single dispatch or function overloading by type.
---
Importing
---
Basic Example
Output:
---
Registering Functions for Different Types
Output:
The correct function is selected automatically based on the argument type.
---
Supporting Multiple Types
Output:
---
Fallback Behavior
If no registered type matches, the original function is used.
Output:
---
Why use
โ Organizes type-specific logic cleanly
โ Avoids long
โ Easy to extend by registering new types
โ Useful in APIs, data processing, and reusable libraries
---
Challenge:
Create a function named:
using `@singledispatch
Each implementation should print a different message describing the received value.
functools.singledispatch DecoratorThe
singledispatch decorator from Python's functools module allows a function to behave differently depending on the type of its first argument.This is known as single dispatch or function overloading by type.
---
Importing
singledispatchfrom functools import singledispatch
---
Basic Example
from functools import singledispatch
@singledispatch
def show(value):
print("Unsupported type")
show(10)
Output:
Unsupported type
---
Registering Functions for Different Types
from functools import singledispatch
@singledispatch
def show(value):
print("Unsupported type")
@show.register
def _(value: int):
print(f"Integer: {value}")
@show.register
def _(value: str):
print(f"String: {value}")
show(100)
show("Python")
Output:
Integer: 100
String: Python
The correct function is selected automatically based on the argument type.
---
Supporting Multiple Types
from functools import singledispatch
@singledispatch
def describe(value):
print("Unknown type")
@describe.register
def _(value: list):
print(f"List with {len(value)} items")
@describe.register
def _(value: dict):
print(f"Dictionary with {len(value)} keys")
describe([1, 2, 3])
describe({"a": 1, "b": 2})
Output:
List with 3 items
Dictionary with 2 keys
---
Fallback Behavior
If no registered type matches, the original function is used.
describe(3.14)
Output:
Unknown type
---
Why use
singledispatch?โ Organizes type-specific logic cleanly
โ Avoids long
if isinstance() chains โ Easy to extend by registering new types
โ Useful in APIs, data processing, and reusable libraries
---
Challenge:
Create a function named:
display()
using `@singledispatch
.
Register implementations for:
- int
- str
- tuple`Each implementation should print a different message describing the received value.
Python coding
๐ Python Tip #61: The functools.singledispatch Decorator The singledispatch decorator from Python's functools module allows a function to behave differently depending on the type of its first argument. This is known as single dispatch or function overloadingโฆ
๐ Python Tip #62: The
The
If the function is called again with the same arguments, the cached result is returned instantly instead of recalculating it.
This technique is called memoization.
---
Importing
---
Basic Example
Output:
Notice that
---
Speeding Up Recursive Functions
Without caching:
With caching:
The cached version is dramatically faster because previously computed values are reused.
---
Limiting Cache Size
Only the most recently used results are kept in the cache.
---
Clearing the Cache
This removes all cached results.
---
Why use
โ Improves performance by avoiding repeated calculations
โ Perfect for recursive algorithms like Fibonacci
โ Easy to use with a single decorator
โ Commonly used in dynamic programming, APIs, and computationally expensive functions
---
Challenge:
Create a recursive function that calculates the factorial of a number.
Then:
1. Decorate it with:
2. Calculate:
3. Call it a second time and observe that the cached result is returned instantly.
functools.lru_cache DecoratorThe
lru_cache decorator from Python's functools module stores the results of function calls.If the function is called again with the same arguments, the cached result is returned instantly instead of recalculating it.
This technique is called memoization.
---
Importing
lru_cachefrom functools import lru_cache
---
Basic Example
from functools import lru_cache
@lru_cache
def square(number):
print("Calculating...")
return number ** 2
print(square(5))
print(square(5))
Output:
Calculating...
25
25
Notice that
"Calculating..." is printed only once because the second call uses the cached result.---
Speeding Up Recursive Functions
Without caching:
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
With caching:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(40))
The cached version is dramatically faster because previously computed values are reused.
---
Limiting Cache Size
from functools import lru_cache
@lru_cache(maxsize=5)
def cube(number):
print("Computing...")
return number ** 3
cube(2)
cube(3)
cube(2)
Only the most recently used results are kept in the cache.
---
Clearing the Cache
from functools import lru_cache
@lru_cache
def multiply(a, b):
return a * b
multiply(2, 3)
multiply.cache_clear()
This removes all cached results.
---
Why use
lru_cache?โ Improves performance by avoiding repeated calculations
โ Perfect for recursive algorithms like Fibonacci
โ Easy to use with a single decorator
โ Commonly used in dynamic programming, APIs, and computationally expensive functions
---
Challenge:
Create a recursive function that calculates the factorial of a number.
Then:
1. Decorate it with:
@lru_cache(maxsize=None)
2. Calculate:
factorial(10)
3. Call it a second time and observe that the cached result is returned instantly.