Python coding
53 subscribers
24 files
11 links
​A technical hub dedicated to Python programming, web development, and software engineering. Learn core syntax, build full-stack projects, and master backend development.
Download Telegram
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 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 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 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 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 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 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 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 dataclass

from 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 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

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
.pdf

- `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 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 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 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

---

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 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 tempfile

import 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 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

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 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 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 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 by type.

---

Importing singledispatch

from 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 functools.lru_cache Decorator

The 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_cache

from 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.
Python coding
🚀 Python Tip #62: The functools.lru_cache Decorator The 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…
💡 Python Tip #63: The functools.cached_property Decorator

The cached_property decorator from Python's functools module computes a property only once.

After the first access, the computed value is stored (cached), so future accesses return the cached result instead of recalculating it.

---

Importing cached_property

from functools import cached_property

---

Basic Example

from functools import cached_property

class Circle:
def __init__(self, radius):
self.radius = radius

@cached_property
def area(self):
print("Calculating area...")
return 3.14159 * self.radius ** 2

circle = Circle(5)

print(circle.area)
print(circle.area)

Output:

Calculating area...
78.53975
78.53975

Notice that "Calculating area..." is printed only once.

---

Without cached_property

class Circle:
def __init__(self, radius):
self.radius = radius

@property
def area(self):
print("Calculating area...")
return 3.14159 * self.radius ** 2

circle = Circle(5)

print(circle.area)
print(circle.area)

Output:

Calculating area...
78.53975
Calculating area...
78.53975

The calculation is performed every time the property is accessed.

---

Clearing the Cached Value

You can remove the cached value using del.

from functools import cached_property

class Square:
def __init__(self, side):
self.side = side

@cached_property
def area(self):
print("Calculating...")
return self.side ** 2

square = Square(4)

print(square.area)

del square.area

print(square.area)

Output:

Calculating...
16
Calculating...
16

After deleting the cached value, it is calculated again the next time it is accessed.

---

Why use cached_property?

✓ Improves performance for expensive calculations
✓ Computes a value only once per object
✓ Keeps code clean and readable
✓ Commonly used in data science, web frameworks, and applications with computationally expensive properties

---

Challenge:

Create a class named:

Rectangle

with the attributes:

width
height

Then:

1. Create a cached_property named:

area

2. Print the area twice.
3. Verify that the calculation occurs only once.