Python

Calling the Claude API from Python: A Practical Guide
Adding a large language model to a Python app usually starts with a five-line script that works on the first try. Then real requirements show up: res
Continue Reading
Working with SQLite in Python Using the sqlite3 Module
SQLite is a full SQL database that lives in a single file, with no server to install or manage. Python ships with the sqlite3 module in the standar
Continue Reading
Scheduling and Automating Tasks with Python Scripts
Writing a script that cleans up old files, pulls a report, or backs up a database is the easy part. Getting it to run every night at 2 a.m., reliably
Continue Reading
Automating Excel Files with Python and openpyxl
Plenty of business processes still run on spreadsheets. Someone exports data every Monday, pastes it into a template, fixes the formatting, adds tota
Continue Reading
Making HTTP Requests in Python with Requests and HTTPX
Almost every Python project ends up talking to something over HTTP: a payment provider, an internal service, a weather API, a webhook. The standard l
Continue Reading
Web Scraping in Python with Requests and Beautiful Soup
Sometimes the data you need is sitting on a web page with no API in sight: a product catalog, a table of results, a list of events. Web scraping is h
Continue Reading
Polars vs Pandas: A Faster DataFrame Library for Python
pandas has been the default DataFrame library in Python for well over a decade. It's everywhere: tutorials, notebooks, data pipelines, and the APIs o
Continue Reading
Data Visualization in Python with Matplotlib and Seaborn
Most Python plotting tutorials start with plt.plot(x, y) and plt.show(), and that works right up until you need two charts side by side, a legend
Continue Reading
NumPy Fundamentals: Arrays, Broadcasting, and Vectorization
NumPy sits underneath almost all numerical Python. pandas DataFrames store their columns in NumPy-style arrays, scikit-learn takes them as input, Mat
Continue Reading
Pandas DataFrames: Filtering, Grouping, and Merging Data
Most real data analysis in pandas comes down to three moves. You filter a table down to the rows you care about, you group it to compute tota
Continue Reading
Deploying a Python Web App with Docker
"It works on my machine" is the oldest problem in deployment, and Python has its own flavor of it: a different Python version on the server, a missin
Continue Reading
Authentication in FastAPI with OAuth2 and JWT
Most APIs need to know who's calling them. FastAPI doesn't ship a complete user system, but it gives you well-designed building blocks: OAuth2 helper
Continue Reading
Using SQLAlchemy 2.0 with Python: ORM Basics and Beyond
SQLAlchemy is the standard way to work with relational databases in Python outside of Django. It powers the database layer of countless Flask and Fas
Continue Reading
Data Validation in Python with Pydantic
Every program eventually reads data it didn't create: JSON from an API, a request body, a config file, a CSV row, environment variables. That data is
Continue Reading
Django vs Flask vs FastAPI: Which Python Web Framework Should You Choose?
Python has three web frameworks that between them cover most new projects: Django, Flask, and FastAPI. All three are mature, well documented, and use
Continue Reading
Building a Web App with Flask: Routes, Templates, and Forms
Flask is the framework people reach for when they want to see every moving part. A complete app can fit in one file, there's no project generator, an
Continue Reading
Getting Started with Django: Building Your First Web App
Django has been around for twenty years, and it's still one of the fastest ways to go from an empty folder to a working, database-backed web app. It
Continue Reading
Building a REST API with FastAPI: A Step-by-Step Guide
FastAPI has become the default choice for new Python APIs, and the reason is easy to see once you use it: you describe your data with type hints, and
Continue Reading
Property-Based Testing in Python with Hypothesis
Example-based tests check the cases you thought of. That's their strength and their limit: if you didn't think of an empty list, a string with an emo
Continue Reading
Measuring Test Coverage in Python with coverage.py
A green test suite tells you that the tests you wrote pass. It doesn't tell you what you didn't write tests for. That untested error branch, the co
Continue Reading
Mocking in Python with unittest.mock
Unit tests should be fast, deterministic, and isolated. Real code, unfortunately, talks to things that are none of those: HTTP APIs that are slow or
Continue Reading
pytest Fixtures and Parametrization: Writing Less Test Code
Most test suites start clean and then slowly fill up with copy-paste. Every test opens a database connection, creates the same three objects, and clo
Continue Reading
Unit Testing in Python with pytest: A Complete Beginner's Guide
If you've ever changed one function and broken something three files away, you already know why tests exist. The hard part is usually getting started
Continue Reading
Managing Multiple Python Versions with pyenv
Sooner or later you need more than one Python. A client project is pinned to 3.11, your own work is on 3.13, and you want to try the free-threaded 3.
Continue Reading
Linting and Formatting Python Code with Ruff
A few years ago, a "properly set up" Python project ran four or five tools on every commit: Flake8 with a handful of plugins for linting, isort for i
Continue Reading
Publishing Your First Python Package to PyPI
At some point a helper module you keep copying between projects deserves a proper home. Publishing it to PyPI means anyone, including future you, can
Continue Reading
Understanding pyproject.toml: Modern Python Project Configuration
For a long time, configuring a Python project meant juggling files. Package metadata lived in setup.py (executable code, which made it hard for too
Continue Reading
Poetry vs uv vs pip-tools: Choosing a Python Dependency Manager
Plain pip installs packages, but it doesn't really manage them. It won't remember which packages you asked for versus which came along as dependenc
Continue Reading
Managing Python Projects with uv: The Fast All-in-One Tool
Setting up a Python project used to involve a small stack of tools: pyenv to get the right Python version, venv to create an environment, pip to in
Continue Reading
Virtual Environments in Python: venv Explained
Every Python project eventually depends on third-party packages, and different projects need different versions of them. One app pins Django 4.2, ano
Continue Reading
Memory Management and Garbage Collection in Python
Python frees you from malloc and free. You create objects, use them, and at some point they disappear. Most of the time you never think about it.
Continue Reading
Speeding Up Python Code: Practical Optimization Techniques
Python has a reputation for being slow, and for tight numeric loops written in pure Python, it is. But most slow Python programs aren't slow because
Continue Reading
Profiling Python Code with cProfile and timeit
When a Python program is slow, the instinct is to start rewriting whatever looks expensive: the regex, the nested loop, the JSON parsing. Most of the
Continue Reading
Using concurrent.futures for Simple Parallelism in Python
Most scripts that need to "do things in parallel" don't need a framework. They have a list of URLs to fetch, files to process, or numbers to crunch,
Continue Reading
Understanding the GIL and Free-Threaded Python
Sooner or later every Python developer writes a multithreaded loop, runs it on an eight-core machine, and watches it finish no faster than the single
Continue Reading
Threading vs Multiprocessing vs Asyncio in Python: Which Should You Use?
Python gives you three built-in ways to do more than one thing at a time: threads, processes, and asyncio. They look similar from a distance, since a
Continue Reading
Asyncio in Python: A Beginner's Guide to Asynchronous Programming
A lot of programs spend most of their time waiting. A web scraper waits for pages to download, an API server waits for the database, a chat bot waits
Continue Reading
Static Type Checking in Python with mypy and Pyright
Type hints on their own don't do anything. Python stores them and moves on, so a function annotated to return str can return None all day long wi
Continue Reading
Generics, Protocols, and TypedDict: Advanced Type Hints in Python
Basic type hints take you a long way. str, list[int], dict[str, float], and X | None cover most function signatures. Then you hit code that's
Continue Reading
Type Hints in Python: A Practical Guide to Static Typing
Python is dynamically typed, and that's a big part of why it's pleasant to write. You don't declare types, you just use values. The downside shows up
Continue Reading
Exception Groups and except* in Python
For most of Python's history, an exception meant exactly one error. That model breaks down in a few situations that are increasingly common: three co
Continue Reading
Creating Custom Exceptions in Python for Clearer Error Handling
Python's built-in exceptions cover a lot of ground. ValueError, KeyError, TypeError, and OSError describe most low-level failures well. But o
Continue Reading
Exception Handling in Python: try, except, else, and finally
Every Python program eventually hits something it didn't plan for: a missing file, a malformed number in user input, a network call that times out. P
Continue Reading
Context Managers in Python: with Statements and contextlib
Most Python developers meet the with statement on day one, usually as with open("data.txt") as f:. It's easy to treat it as "the way you open fil
Continue Reading
Iterators and the Iterator Protocol in Python
A for loop in Python works on lists, strings, dictionaries, files, database cursors, range objects, and anything else that knows how to hand out
Continue Reading
Closures in Python: How Inner Functions Remember Their Environment
Here's something that looks like it shouldn't work. A function creates a local variable, defines an inner function that uses it, and returns the inne
Continue Reading
Python Decorators Explained: From Basics to Decorators with Arguments
Decorators are everywhere in Python. @property, @dataclass, @app.get("/"), @pytest.fixture, @functools.cache: one line above a function or
Continue Reading
Metaclasses in Python Explained Without the Headache
Metaclasses have a reputation. Tim Peters famously said they're "deeper magic than 99% of users should ever worry about", and most tutorials respond
Continue Reading
Descriptors in Python: The Mechanism Behind Properties and Methods
You've used descriptors many times, probably without knowing it. Every @property, every @classmethod and @staticmethod, every `functools.cached
Continue Reading
__slots__ in Python: Saving Memory in Attribute-Heavy Classes
Most Python objects carry a small dictionary around with them. It's what lets you do obj.anything = 42 on almost any instance, and it's convenient.
Continue Reading
Composition vs Inheritance in Python: Designing Flexible Classes
Inheritance is usually the first tool people learn for reusing code in classes, so it tends to become the tool for everything. Need an email notifier
Continue Reading
Enums in Python: Replacing Magic Strings and Numbers
Every codebase has them: if status == "shiped":, if role == 3:, set_mode("fast"). Magic strings and numbers work right up until someone makes a
Continue Reading
Abstract Base Classes in Python with the abc Module
Python leans on duck typing: if an object has the method you need, you call it and move on. That works well until you have a family of classes that a
Continue Reading
Dataclasses in Python: Less Boilerplate, More Clarity
A lot of classes exist mainly to hold data: a product with a SKU and a price, a config object with a host and a port, a point with x and y. Writing t
Continue Reading
Class Methods vs Static Methods vs Instance Methods in Python
Python classes can have three kinds of methods. Regular instance methods are the ones you write all the time. Then there are methods decorated with `
Continue Reading
@property in Python: Getters, Setters, and Computed Attributes
If you've come to Python from Java or C#, your instinct when writing a class might be to make every field private and add get_price() and `set_pric
Continue Reading
Python Dunder Methods: Making Your Classes Feel Built-In
Why does len(my_list) work, but len(my_object) raises a TypeError? Why can you add two numbers with + and compare two strings with <, but y
Continue Reading
Inheritance and super() in Python: How Method Resolution Order Works
Inheritance looks simple when there's one parent class: the child gets the parent's methods, overrides a few, and calls super() to reach the origin
Continue Reading
Classes and Objects in Python: A Practical Introduction to OOP
You've been using objects since your first line of Python. A string is an object with methods like .upper(). A list is an object you .append() to
Continue Reading
Running Shell Commands from Python with subprocess
Sooner or later a Python script needs to call another program: run git to find the current commit, invoke ffmpeg to convert a video, call `pg_dum
Continue Reading
Logging in Python: Moving Beyond print()
Every Python program starts out debugging with print(). It's immediate and it works. Then the program grows: it runs on a server where nobody watch
Continue Reading
Building Command-Line Tools in Python with argparse
Most Python scripts start life with a hardcoded file name at the top, and then someone asks if it can take a different file. The quick fix is `sys.ar
Continue Reading
Python's heapq and bisect Modules: Priority Queues and Sorted Lists
A lot of code needs data in order, but not always fully sorted all the time. A job scheduler only needs to know which task is most urgent right now
Continue Reading
Working with JSON in Python: Serialization, Custom Encoders, and Pitfalls
JSON is the format Python programs use to talk to almost everything else: web APIs, JavaScript frontends, config files, message queues, and databases
Continue Reading
Regular Expressions in Python with the re Module
Regular expressions are a small language for describing patterns in text: "four digits, a dash, two digits", "a word that starts with a capital lette
Continue Reading
pathlib in Python: The Modern Way to Work with File Paths
For a long time, working with file paths in Python meant treating them as strings and passing them through a scattered set of functions: `os.path.joi
Continue Reading
File Handling in Python: Reading and Writing Text, CSV, and JSON
Reading and writing files is one of the first things most people do in Python, and one of the places where small mistakes quietly cause trouble later
Continue Reading
Working with Dates and Times in Python Using datetime and zoneinfo
Dates and times look simple until a user in another country books a meeting, a scheduled job runs twice on the night the clocks change, or a timestam
Continue Reading
functools in Python: partial, lru_cache, reduce, and wraps
Python treats functions as ordinary values. You can pass them around, store them in dicts, return them from other functions, and wrap them in new beh
Continue Reading
Mastering itertools in Python: Efficient Iteration Recipes
Most Python loops follow a handful of shapes: flatten some nested lists, take the first N items, walk through pairs of neighbors, split work into chu
Continue Reading
The collections Module: Counter, defaultdict, deque, and namedtuple
Python's built-in list, dict, set, and tuple cover most of what you need. But a surprising amount of everyday code is the same few patterns w
Continue Reading
Sets in Python: Fast Membership Tests and Set Operations
Sets are the most underused of Python's built-in collections. Plenty of code checks if item in some_list inside a loop, deduplicates with nested lo
Continue Reading
Python Dictionaries Deep Dive: Ordering, Views, and Merging
Dictionaries are everywhere in Python. Keyword arguments, module namespaces, object attributes, JSON payloads, and configuration all end up as dicts,
Continue Reading
Lists vs Tuples in Python: Choosing the Right Sequence
Lists and tuples are Python's two general-purpose sequence types. Both hold ordered collections of any objects, both support indexing, slicing, itera
Continue Reading
Working with Bytes, Encoding, and Unicode in Python
Text handling in Python 3 is built on a clean split: str holds text as a sequence of Unicode characters, and bytes holds raw binary data. Convert
Continue Reading
Python Strings Deep Dive: Methods Every Developer Should Know
Python's str type has around 47 methods. Most developers use five or six of them regularly and reach for regular expressions or hand-written loops
Continue Reading
Slicing in Python: Start, Stop, Step, and Negative Indices
Slicing is one of the first things you learn in Python and one of the last things you fully master. items[1:3] is easy. items[-1:-4:-1], `items[4
Continue Reading
Python's enumerate, zip, and range: Looping Like a Pro
If you came to Python from C, Java, or JavaScript, your first loops probably looked like for i in range(len(items)): followed by items[i] everywh
Continue Reading
Lambda Functions in Python: Uses, Limits, and Better Alternatives
Python's lambda keyword lets you create a small function inline, without giving it a name. It's handy when an API wants a function and the logic fi
Continue Reading
Default Argument Pitfalls in Python: The Mutable Default Trap
Almost every Python developer hits this bug once. You write a function with a list as its default argument, call it a few times, and the list starts
Continue Reading
*args and **kwargs in Python: Flexible Function Signatures
You've seen def wrapper(*args, **kwargs): in decorators, and probably super().__init__(**kwargs) in class hierarchies. These two parameters let a
Continue Reading
Python Scope Explained: LEGB, global, and nonlocal
Every time Python sees a name like count or len, it has to figure out which variable that name refers to. Most of the time the answer is obvious
Continue Reading
Structural Pattern Matching in Python with match and case
Python 3.10 added the match statement, and many developers filed it away as "Python finally got switch". That undersells it. match can compare
Continue Reading
The Walrus Operator (:=) in Python: When It Helps and When It Hurts
The walrus operator, :=, landed in Python 3.8 after one of the most heated debates in the language's history. Its official name is the **assignment
Continue Reading
Unpacking in Python: Starred Expressions, Swaps, and Multiple Assignment
Unpacking is one of those Python features you use long before you know its name. for key, value in d.items(): is unpacking. So is x, y = point, a
Continue Reading
List, Dict, and Set Comprehensions in Python: Writing Cleaner Loops
A large share of the loops in any Python codebase do the same thing: start with an empty list or dict, loop over something, maybe skip a few items, a
Continue Reading
f-Strings in Python: Formatting Tricks You Probably Aren't Using
Most Python developers use f-strings every day, but usually only for the simplest job: dropping a variable into a string. f"Hello, {name}" is nice,
Continue Reading
Understanding Python's Truthiness: How if Decides What's True
In Python you can write if items: instead of if len(items) > 0:, and if name: instead of if name != "":. The condition in an if doesn't hav
Continue Reading
Python Variables and Mutability: Why Lists Change and Strings Don't
Sooner or later every Python developer hits this: you copy a list into a new variable, change the "copy", and the original changes too. Then you try
Continue Reading
What is a Generator in Python? How is it Different from a Regular Function?
Generators are a powerful feature in Python that allow for efficient iterat
Continue Reading
How to debug a Python program?
Debugging is a crucial part of the development process. It helps you find and fix errors in your code, ensuring that your program runs correctly. Pyt
Continue Reading
How to use the __init__ method?
In the realm of object-oriented programming, the init method plays a crucial role in the initialization process of objects. It is a special method th
Continue Reading
What is PIP and How Do I Use It?
PIP (Pip Installs Packages) is the standard package management system for Python. It ena
Continue Reading
How to Convert Between Data Types in Python ?
Python is a dynamically typed language, meaning that variables can change data types as needed. However, sometimes it'
Continue Reading
What are Python Modules and Packages?
Python modules and packages are fundamental tools that help in organizing and structuring Python code. They enable code re
Continue Reading
Python's Best Practices for Coding
Writing clean, readable, and maintainable code is crucial for any successful software project. Python, with its emphasis on readability and simplicit
Continue Reading
What are Python's Main Features?
Python is a powerful and versatile programming language that is widely used across various domains. Its design philosophy
Continue Reading
What is the difference between Python 2 and Python 3?
Python is a versatile programming language that has undergone significant changes over the years. The most notable of
Continue Reading
How to use Python with databases?
Python is a versatile language that is often used for backend development, data analysis, and scripting. One of its powerful c
Continue Reading
How to Use Python for Data Analysis?
Python has become a dominant language in the field of data analysis due to its simplicity, readability, and extensive ecosystem of powerful libraries
Continue Reading