Skip to content

Topic archive

Python

A versatile programming language with readable syntax, widely used in web development, automation, data science, and AI.

113 articles
Python 02 Sep 2026 9 min read

Practical Queues and Sliding Windows with Python deque

Many programs need a sequence that changes at both ends. A worker may append new jobs on the right and consume the oldest job from the left. A monitoring loop may keep only the most recent measurements. An algorithm may need to add or remove candidates from either side while scanning an input stream. A Python list is excellent when random access and operations near the right end dominate. It is a poor fit for a FIFO queue that repeatedly removes index zero, because the remaining list elements must be shifted. The collections.deque type is designed for efficient appends and pops at both ends.

Python 02 Sep 2026 10 min read

Practical Priority Queues in Python with heapq

Many programs need to repeatedly choose the most important pending item rather than process items in insertion order. Schedulers pick the next deadline, graph algorithms choose the lowest-cost candidate, and streaming systems keep only the best few observations seen so far. A sorted list can solve these problems, but maintaining full ordering is often unnecessary. Python’s heapq module provides a heap: a compact data structure that keeps one extreme element immediately available while doing only enough work to preserve that property.

Python 02 Sep 2026 8 min read

Practical Function Specialization in Python with functools.partial

Functions often expose more parameters than a particular caller needs to choose. A parser may always use the same base, a callback may need access to one application object, or a formatting function may use a fixed prefix throughout one subsystem. Python’s functools.partial() can turn such a general callable into a more focused callable by binding some arguments in advance. The result remains callable, so it can be passed to APIs that expect a function-like object without introducing a wrapper function solely to carry configuration.

Python 02 Sep 2026 9 min read

Practical File Paths in Python with pathlib

Filesystem paths look simple until code has to run from a different working directory, support multiple operating systems, handle symbolic links, or distinguish path manipulation from actual filesystem access. Python’s pathlib module provides path objects that make those distinctions explicit. Instead of repeatedly joining and splitting strings, code can express operations such as “the parent directory,” “this file’s suffix,” or “this path relative to that directory” directly. The most useful habit is not merely replacing os.path calls with methods. It is understanding which pathlib operations are lexical, which consult the filesystem, and when resolving a path changes its meaning.

Python 02 Sep 2026 8 min read

Maintain Sorted Sequences in Python with bisect

A sorted list is useful when a program needs ordered iteration and frequent searches but does not require the repeated minimum extraction of a priority queue. Python’s bisect module provides binary-search operations for this exact representation. The module does not create a special container. It works with an existing sorted sequence and finds the position where a value belongs. That makes it small and predictable, but it also means the caller is responsible for preserving sorted order and understanding that inserting into a Python list still requires moving elements.

Python 02 Sep 2026 4 min read

Cache Pure Work in Python with functools.cache and lru_cache

Caching can turn repeated expensive work into a dictionary lookup, but it can also return stale data or grow memory without bound. Python’s functools module provides two convenient memoization decorators: lru_cache and cache. functools.cache has been available since Python 3.9. It is effectively an unbounded memoization cache. lru_cache adds a configurable size limit and eviction behavior. Cache functions, not arbitrary side effects Memoization works best when a function behaves like a pure function: the result depends only on its arguments.

Python 01 Sep 2026 3 min read

Use Python Protocols for Structural Typing at API Boundaries

Python often relies on duck typing: if an object supports the operation a function needs, its concrete class does not matter. typing.Protocol gives static type checkers a way to describe that idea explicitly without requiring implementations to inherit from a shared base class. Define the behavior you consume from typing import Protocol class ByteWriter(Protocol): def write(self, data: bytes) -> int: ... def emit_header(writer: ByteWriter) -> None: writer.write(b"NLR1") Any statically compatible object can satisfy ByteWriter, even if its class never mentions the protocol.

Python 01 Sep 2026 5 min read

Python Protocols and Structural Subtyping for Flexible APIs

Python code often depends on behavior rather than a specific class hierarchy. A function may only need an object with a send() method, a read() method, or a pair of repository operations. typing.Protocol lets type checkers describe those behavioral requirements directly. A class satisfies a protocol by having compatible members; it does not need to inherit from the protocol. This is structural subtyping: “if it has the required shape, it can be used here.”

Python 01 Sep 2026 4 min read

Python Context Managers for Reliable Resource Cleanup

Python’s with statement is more than convenient file syntax. It is a general protocol for pairing setup with guaranteed cleanup, including when code exits early or raises an exception. Understanding context managers makes resource lifetimes visible and prevents a broad class of leaked files, locks, connections, and temporary state. Why try/finally is the foundation Without a context manager, safe cleanup often looks like this: file = open("input.txt", encoding="utf-8") try: data = file.read() finally: file.close() The finally block runs whether the read succeeds or raises. A with statement packages that pattern:

Python 01 Sep 2026 3 min read

Design Value Objects with Python Dataclasses

Python dictionaries are convenient for passing a few values around, but they become fragile when a value has invariants or behavior that deserves a name. dataclasses can express small domain value objects without repetitive constructors and representation methods. Start with domain meaning A price represented as a dictionary is easy to misuse: price = {"amount": 1299, "currency": "USD"} Any caller can omit a key or accidentally mix cents and dollars. A value object makes the contract explicit:

Python Updated 02 Sep 2025 2 min read

Understanding Polymorphism in Python

Polymorphism means that different objects can respond to the same operation in their own way. In Python, this often appears through inheritance, method overriding, protocols, and duck typing. Method Overriding with Inheritance class Animal: def sound(self): return "unknown sound" class Dog(Animal): def sound(self): return "bark" class Cat(Animal): def sound(self): return "meow" Code can treat each object through the shared sound() interface:

Python Updated 02 Sep 2025 2 min read

Understanding Iterators in Python

Iterators are a core Python concept behind for loops, generators, file objects, and many standard-library APIs. They provide one item at a time instead of requiring every result to be materialized in memory at once. Iterable vs Iterator An iterable is an object you can pass to iter(), such as a list, tuple, dictionary, set, or string. An iterator is an object that produces successive values through next(). numbers = [1, 2, 3] iterator = iter(numbers) print(next(iterator)) # 1 print(next(iterator)) # 2 print(next(iterator)) # 3 Calling next() again raises StopIteration because the iterator is exhausted.

Python Updated 02 Sep 2025 2 min read

Understanding Classes and Objects in Python

Python supports object-oriented programming through classes and objects. A class defines behavior and data structure, while an object is a concrete instance of that class. Define a Class class Car: def __init__(self, make, model): self.make = make self.model = model def display_info(self): print(f"Car Make: {self.make}, Model: {self.model}") __init__() initializes a new instance after it is created. The first parameter, conventionally named self, refers to the instance receiving the method call.

Python Updated 02 Sep 2025 3 min read

Python String Formatting: A Practical Guide

String formatting lets Python programs combine values with readable text while controlling alignment, precision, numeric separators, dates, and other presentation details. Modern Python generally favors f-strings for application code. 1. F-Strings Available since Python 3.6, f-strings embed expressions directly: name = "Alice" age = 30 message = f"{name} is {age} years old." print(message) Expressions can be evaluated inside the braces:

Python Updated 02 Sep 2025 3 min read

Python RegEx: A Practical Guide to Regular Expressions

Regular expressions describe text patterns for searching, validating, extracting, splitting, and replacing strings. Python provides regular-expression support through the standard-library re module. Start with Raw Strings Regex patterns often contain backslashes. Raw string literals keep them readable: import re pattern = r"\d+" Without the r prefix, Python string escaping and regex escaping can interact in confusing ways.

Python Updated 02 Sep 2025 2 min read

Python Modules: Organizing Code Effectively

A Python module is a .py file that groups related functions, classes, constants, and other definitions. Splitting a growing program into modules makes code easier to navigate, test, reuse, and maintain. Create a Module Create my_module.py: def greet(name): return f"Hello, {name}!" def add(a, b): return a + b Then import it from another file in the same importable project location:

Python Updated 02 Sep 2025 2 min read

Python Math: Essential Functions and Operations for Beginners

Python’s standard math module provides functions and constants for floating-point mathematics, including square roots, logarithms, trigonometry, rounding helpers, and combinatorics. Import the Module import math Square Roots and Powers print(math.sqrt(16)) # 4.0 print(math.pow(2, 3)) # 8.0 print(2 ** 3) # 8 For ordinary exponentiation, the ** operator is usually simpler. math.pow() converts its arguments to floating point and returns a float.

Python Updated 02 Sep 2025 2 min read

Python Inheritance

Inheritance lets one Python class reuse and specialize behavior defined by another class. It can be useful when classes have a genuine “is-a” relationship and share a stable interface. Basic Inheritance class Animal: def sound(self): return "unknown" class Dog(Animal): def sound(self): return "bark" print(Dog().sound()) Dog inherits from Animal and overrides sound() with behavior specific to dogs.

Python Updated 02 Sep 2025 3 min read

Python `try-except`: A Practical Error-Handling Guide

Exceptions let Python programs report failures without encoding every error as a special return value. try and except provide structured recovery when an operation has expected failure modes. Basic try-except try: number = int("not-a-number") except ValueError: print("The value is not a valid integer.") When int() raises ValueError, Python skips the remaining code in the try block and runs the matching handler.

Python Updated 02 Sep 2025 2 min read

JSON in Python: Working with JSON Data

JSON (JavaScript Object Notation) is a text format for structured data exchange. Python includes the json module in the standard library, so common JSON operations require no third-party dependency. Python Objects to JSON Strings Use json.dumps() to serialize a Python object: import json data = { "name": "Alice", "age": 25, "city": "New York", } json_string = json.dumps(data) print(json_string) For readable output:

Python Updated 02 Sep 2025 2 min read

Understanding Conditional Expressions in Python

Python does not use the condition ? a : b syntax found in languages such as C or JavaScript. Instead, it provides a conditional expression that reads naturally from left to right. Basic Syntax value_if_true if condition else value_if_false For example:

Python Updated 02 Sep 2025 2 min read

Understanding `@staticmethod` vs `@classmethod` in Python

Python provides @staticmethod and @classmethod for methods that do not operate on one specific instance. They look similar at first, but they receive different context and solve different problems. @staticmethod A static method receives no implicit self or cls argument: class Temperature: @staticmethod def celsius_to_fahrenheit(value): return value * 9 / 5 + 32 print(Temperature.celsius_to_fahrenheit(20)) Use a static method when a function logically belongs in the class namespace but does not need instance or class state.

Python Updated 02 Sep 2025 2 min read

Understanding `__str__` vs `__repr__` in Python

Python provides __str__() and __repr__() so classes can control how their instances appear as text. They serve related but different audiences. __str__: Human-Friendly Output str(obj) and usually print(obj) use __str__(): class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name}, age {self.age}" person = Person("Alice", 30) print(person) Output:

Python Updated 02 Sep 2025 2 min read

Understanding `__init__.py` in Python

The __init__.py file is commonly used to define a regular Python package and control what happens when that package is imported. It can be empty, expose a package-level API, define metadata, or run lightweight initialization code. 1. A Basic Package Consider this structure: my_package/ ├── __init__.py ├── module1.py └── module2.py With __init__.py present, my_package is a regular package and its modules can be imported normally: