Bookmarks
ReferenceBackendData & AIVerified

Python

Python is a general-purpose programming language for backends, scripting and data. Covers syntax, types, functions, exceptions, venv, pip and asyncio.

checked 31 Oct · next check 7 Nov · 47 min read

Sections
13
Reading
47 min
Current version
3.15.2
Written from
docs.python.org/3

Check status of the reference

Verified 31 Oct · next check 7 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Python is and how it works

Python is an interpreted general-purpose programming language: programs need no separate build step, as the interpreter runs source code directly. The reference implementation, CPython, is distributed by python.org; “Python” usually means CPython.

Python is used to automate routine work (replacing text in a hundred files, sorting photos into folders), to write tests, utilities and applications, and as an extension language inside other programs. High-level types — lists, dictionaries, sets — and a large standard library make Python programs shorter than equivalent C or Java code. Speed-critical parts go into C modules that plug into the interpreter. For web development, see the Django and FastAPI references; for data analysis, the pandas reference.

A program runs in two steps within one process. The compiler translates source code into bytecode, CPython’s internal representation of the program, and the virtual machine executes it instruction by instruction. Bytecode of imported modules is cached in .pyc files, so loading a module again skips compilation. Bytecode is an implementation detail: it differs between Python versions and between interpreters.

Compilation and execution share one python3 process; there is no separate build step.

The dis module shows the bytecode of any function:

pythonapp.py
import dis def area(width, height):    return width * height dis.dis(area)
textexample output
  3           RESUME                   0   4           LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (width, height)              BINARY_OP                5 (*)              RETURN_VALUE

Variables and arguments have no declared types: a name can refer to an object of any type. The interpreter does not check type hints (def area(width: float) -> float); external type checkers and code editors read them. In the standard CPython build, only one thread executes bytecode at a time — this is the global interpreter lock (GIL). A free-threaded build without the GIL also exists; see “asyncio, threads and processes”.

How Python differs from Go and Node.js

AspectPythonGoNode.js
How it runsthe interpreter executes source code; types are not checked in advancethe compiler checks types and builds an executablethe runtime executes JavaScript on the V8 engine
What you deploysource code and an interpreter of the right versionone statically linked binary with the Go runtime insidesource code and Node.js
Concurrencythreads (with the GIL), processes, asynciogoroutines on top of OS threadsone process with non-blocking I/O
Strengthsautomation, tests, gluing existing libraries togethernetwork services, loads that use every coreservers in the same language as the frontend

Choose Python when development speed and ready-made libraries matter most; Go when you need one file to deploy and work on all cores; Node.js when the team already writes its frontend in JavaScript.

What to know first

  • The command line: running programs, the current directory, the PATH variable — see the Linux reference
  • Git basics: a project lives in a repository, and the virtual environment directory stays out of it — see the Git reference
  • A code editor with Python highlighting and indentation checks

Section sources

the section is written from these pages

Cheat sheet

Everyday Python constructs and commands, grouped by task: environments and packages, strings, lists and dictionaries, loops, functions, files and JSON, exceptions.

Environments and running code

TaskCode
Create an environment in .venvpython3 -m venv .venv
Activate in bash and zshsource .venv/bin/activate
Activate in PowerShell.venv\Scripts\Activate.ps1
Install a packagepython -m pip install requests
Save dependenciespython -m pip freeze > requirements.txt
Install dependenciespython -m pip install -r requirements.txt
Run a module as a programpython -m pip --version
Leave the environmentdeactivate

Strings and conversions

TaskCode
Insert valuesf"{name}: {total}"
Two decimal placesf"{price:.2f}"
Name and value for debuggingf"{total=}"
Split and joinline.split(","), ", ".join(parts)
Trim whitespaces.strip()
Replace a substrings.replace("http:", "https:")
First 3 characters, all but the lasts[:3], s[:-1]
String to number and backint("42"), float("1.5"), str(42)
Check the typeisinstance(x, str)

Lists and dictionaries

TaskCode
Append one item, append severalitems.append(x), items.extend([4, 5])
Remove and return the last itemitems.pop()
Sort in place, get a sorted copyitems.sort(), sorted(items)
Length, membershiplen(items), x in items
Value by key or a defaultconfig.get("port", 8000)
Iterate over key-value pairsfor key, value in config.items():
Merge dictionariessettings = defaults | overrides
Delete a keydel config["debug"]

Loops and comprehensions

TaskCode
Numbers from 0 to 9for i in range(10):
Number the itemsfor i, item in enumerate(items, start=1):
Two lists in parallelfor name, age in zip(names, ages):
New list[x * 2 for x in nums]
With a filter[x for x in nums if x > 0]
Dictionary{name: len(name) for name in names}
Flatten nested lists (since Python 3.15)[*row for row in rows]
Loop while a condition holdswhile attempts < 3:

Functions

TaskCode
Default valuedef connect(host, port=5432):
Keyword-only argumentsdef run(cmd, *, timeout=10):
Any number of argumentsdef log(*args, **kwargs):
Unpack in a callconnect(*pair), connect(**options)
Short sort key functionsorted(users, key=lambda u: u.age)
Type hintsdef area(w: float, h: float) -> float:

Files, JSON, input and output

TaskCode
Read a whole filewith open("notes.txt", encoding="utf-8") as f: text = f.read()
Read line by linefor line in f:
Write a filewith open("out.txt", "w", encoding="utf-8") as f: f.write(text)
Append to a file"a" mode instead of "w"
Object to a JSON string and backjson.dumps(data), json.loads(text)
JSON to and from a filejson.dump(data, f), json.load(f)

Exceptions

TaskCode
Catch a specific exceptionexcept ValueError as e:
Several types (since Python 3.14)except ValueError, TypeError:
Always runfinally:
Raise your ownraise ValueError("port must be > 0")
Keep the causeraise ConfigError("bad config") from e

Section sources

the section is written from these pages

Installation and first run

On Linux, Python comes from the distribution’s packages; on macOS, from the python.org installer; on Windows, through the Python install manager. Each project’s packages go into its own virtual environment, created with the venv module, not into the system.

Linux

Most Linux distributions come with Python as the python3 command; the rest have it in their repositories. The distribution package may lack the branch or features you need. Then build Python from source: download the archive from python.org, install the build dependencies and run in its directory:

bashsource directory
./configuremakesudo make altinstall

macOS and Windows

On macOS, download the .pkg installer from the python.org downloads page and run it. Python itself goes to /Library/Frameworks/Python.framework, the python3 and python3.15 links to /usr/local/bin/, and IDLE and Python Launcher to the /Applications/Python 3.15/ folder. Finally, double-click Install Certificates.command in that folder: the script downloads and installs root SSL certificates for this Python. Leave Apple’s system /usr/bin/python3 alone — Xcode tools rely on it.

On Windows, use the official Python install manager from the Microsoft Store or the python.org downloads page. It provides the python and py commands: py list shows the installed versions, and py -V:3.15 runs a specific one.

Checking the installation

python3 --version prints the full version number; sys.version_info shows the interpreter branch:

bashterminal
python3 -c "import sys; print(sys.version_info[:2])"
textexample output
(3, 15)

Interactive mode (REPL)

python3 without arguments opens interactive mode: a line after the >>> prompt runs at once, and ... marks a continuation line of a multi-line statement. Command history, line editing and Tab completion work. Exit with quit(), Ctrl+D on Linux and macOS, or Ctrl+Z on Windows.

consoleREPL
>>> 2 ** 1001267650600228229401496703205376>>> name = "Python">>> f"Hello, {name}!"'Hello, Python!'

Running a file or a module

To run a file, pass its name to the interpreter. The -m flag runs a module by name as a program, as in python3 -m venv and python3 -m pip. -c executes a command given as a string, and -i stays in interactive mode after the file has run.

bashterminal
python3 app.pypython3 -m pip --versionpython3 -c "import sys; print(sys.executable)"python3 -i app.py

Virtual environments (venv)

A virtual environment is a directory with a link to the base interpreter (or a copy of it) and its own packages, isolated from the system Python and other projects. It is usually named .venv and lives in the project root. Environments are disposable: rather than copying or moving one, create it anew.

bashLinux and macOS
python3 -m venv .venvsource .venv/bin/activate# pip installs packages into .venv, not the systempython -m pip install requestsdeactivate
powershellWindows, PowerShell
python -m venv .venv.venv\Scripts\Activate.ps1python -m pip install requests

After activation, python and pip come from .venv, and the shell prompt shows the environment name. Activation is optional: calling .venv/bin/python directly works too, which is how cron jobs and services run programs.

If venv cannot create an environment or pip refuses to install a package, look up the error in “Common errors and troubleshooting”.

Section sources

the section is written from these pages

Syntax and control flow

A Python program is a sequence of statements, one per line. Blocks are marked by indentation, not braces: everything belonging to an if, a for or a function is indented by the same number of spaces. By convention, an indent is 4 spaces, with no tabs.

pythonfib.py
# a comment runs from the hash to the end of the linelimit = 100total = 0a, b = 0, 1while a < limit:    total += a    a, b = b, a + bprint(total)
textexample output
232

The line a, b = b, a + b is multiple assignment: the right-hand side is evaluated in full, then unpacked into the names. A long expression can be wrapped inside parentheses, brackets or braces, where line breaks do not matter. A backslash \ at the end of a line also joins lines, but cannot be followed by a comment. Do not mix tabs and spaces in one file’s indentation: if an indent’s meaning depends on the tab width, the interpreter raises TabError.

Conditions: if, elif, else

pythonstatus.py
status = 404if 200 <= status < 300:    print("ok")elif status < 500:    print("client error")else:    print("server error")

elif is short for “else if”; there can be any number of such branches, and else is optional. Comparisons can be chained: 200 <= status < 300. and and or evaluate operands left to right, stop as soon as the result is known and return the operand itself: name or "guest" gives "guest" if name is an empty string.

Loops: for and while

for iterates over the items of a sequence or other iterable in order, not over a counter. For numbers, use range(): the end value is excluded. enumerate() adds each item’s number, and zip() walks several lists in parallel.

pythonloops.py
langs = ["python", "go", "sql"]for i, lang in enumerate(langs, start=1):    print(i, lang) for n in range(10, 0, -3):    print(n, end=" ")
textexample output
1 python2 go3 sql10 7 4 1

break exits the innermost loop, continue jumps to the next iteration, and pass is an empty statement where the syntax requires a body. A loop can have an else branch, which runs if the loop ends without break — a way to write a search without an extra flag.

pythonports.py
busy = {8000, 8001}for port in range(8000, 8010):    if port not in busy:        breakelse:    raise RuntimeError("no free port")print("free port:", port)

Pattern matching: match

match compares a value with the patterns of its case branches in turn and runs the first that fits. Unlike switch in other languages, a pattern takes the value apart — a sequence, a mapping, a class instance — and binds the parts to names. The _ pattern matches anything, | combines alternatives, and if after a pattern adds a condition.

pythoncommands.py
def handle(command):    match command.split():        case ["quit" | "exit"]:            return "bye"        case ["load", filename]:            return f"loading {filename}"        case ["move", x, y] if x.isdigit() and y.isdigit():            return f"moving to {x}, {y}"        case _:            return "unknown command" print(handle("load data.csv"))
pythonevents.py
event = {"type": "click", "x": 10, "y": 20, "button": "left"}match event:    case {"type": "click", "x": x, "y": y}:        print("click at", x, y)    case {"type": "key", "key": key}:        print("key", key)

A name in a pattern (filename, x) captures the value instead of comparing it. To compare with a constant, use a dotted name: case Color.RED:. A mapping pattern checks only the listed keys and ignores extra ones. True, False and None are compared by identity, other literals by equality.

Comprehensions

A comprehension builds a list, set or dictionary in one expression: what to include, where to take it from and, optionally, a filter condition. Its for and if clauses follow the order of nested loops. Parentheses instead of square brackets give a generator expression; generators are covered in “Functions, arguments and scope”.

pythoncomprehensions.py
nums = [3, -1, 4, -1, 5]squares = [n * n for n in nums if n > 0]unique = {abs(n) for n in nums}lengths = {name: len(name) for name in ["go", "python"]}total = sum(n * n for n in nums)print(squares, unique, lengths, total)
textexample output
[9, 16, 25] {1, 3, 4, 5} {'go': 2, 'python': 6} 52

Since Python 3.15, comprehensions support * and ** unpacking, which flattens nested lists and merges dictionaries without a second for.

pythonPython 3.15
rows = [[1, 2], [3], [4, 5]]flat = [*row for row in rows]layers = [{"debug": False, "port": 80}, {"port": 8000}]config = {**layer for layer in layers}print(flat, config)
textexample output
[1, 2, 3, 4, 5] {'debug': False, 'port': 8000}

The := operator and f-strings

The := operator assigns a value inside an expression. It is useful in if and while conditions where a value must be both tested and used afterwards. Unlike C, Python does not allow a plain = inside an expression.

pythonwalrus.py
data = [5, 12, 7, 30]if (n := len(data)) > 3:    print(f"too many items: {n}")

An f-string (f"...") substitutes the values of expressions in braces immediately and produces an ordinary str. A t-string (t"...", since Python 3.14) looks the same but produces a Template object: the text and the interpolated values are stored separately, and the code receiving the template decides how to process and join them.

Propertyf-stringt-string
Prefixf or Ft or T, since Python 3.14
Resultstrstring.templatelib.Template
Format spec {x:.2f}applied at once via format()kept in the Interpolation object
When to useoutput, messages, file nameswhen values need processing before joining
pythonstrings.py
price = 1234.5print(f"Total: {price:,.2f} UZS")template = t"Total: {price:,.2f}"print(type(template).__name__, template.values)
textexample output
Total: 1,234.50 UZSTemplate (1234.5,)

Section sources

the section is written from these pages

Built-in types and data structures

Every value in Python is an object of some type: numbers int and float, strings str, collections list, tuple, dict, set. Types are mutable or immutable: a list can be changed in place, but a number, string or tuple cannot — operations on them create a new object.

A variable is a name that refers to an object, not a box holding a copy of a value. The assignment b = a copies nothing: both names point to the same object. If the object is mutable, a change made through one name is visible through the other. For an immutable object, a “change” like y += 1 creates a new object and rebinds the name to it.

Assignment binds a name to an object and copies nothing.
pythonnames.py
a = [1, 2, 3]b = ab.append(4)print(a, a is b) x = 1y = xy += 1print(x, y)
textexample output
[1, 2, 3, 4] True1 2

is tests identity — whether both sides are the same object — and == tests equality of values. For an independent copy, make one explicitly: list.copy(), dict.copy() and the slice a[:] copy only the top level, while copy.deepcopy() also copies nested objects.

pythoncopies.py
import copy config = {"hosts": ["a", "b"]}shallow = config.copy()deep = copy.deepcopy(config)config["hosts"].append("c")print(shallow["hosts"], deep["hosts"])
textexample output
['a', 'b', 'c'] ['a', 'b']

Collections

TypeMutableOrderExample
listyesby position[1, 2, 3]
tuplenoby position(1, "a")
dictyeskey insertion order{"port": 80}
frozendict, since Python 3.15nokey insertion orderfrozendict(port=80)
setyesnone{1, 2}
frozensetnononefrozenset({1, 2})

Only hashable objects can be dictionary keys or set elements: numbers, strings, tuples of hashable values, frozenset and, since Python 3.15, frozendict if its keys and values are hashable. A list or a regular dictionary cannot be a key. The | operator merges dictionaries; on duplicate keys, the right-hand value wins.

Numbers, bool and None

int holds integers of any size, with no overflow. float is a binary floating-point number (usually a C double), so decimal fractions are stored with a small error; for exact decimal arithmetic, use decimal.Decimal. bool is a subclass of int with two values, True and False. None is the single object meaning “no value”; test for it with is None.

pythonnumbers.py
print(2 ** 100)print(7 // 2, 7 % 2, 7 / 2)print(isinstance(True, int))print(int("42") + float("1.5"))
textexample output
12676506002282294014967032053763 1 3.5True43.5

Strings and bytes

str is an immutable sequence of Unicode characters, bytes a sequence of bytes. Converting between them always takes an encoding: str.encode() and bytes.decode() default to UTF-8. String methods return a new string and leave the original intact. Files opened with open() in text mode are decoded too: since Python 3.15 the default is UTF-8 on every system, but an explicit encoding="utf-8" is still more reliable.

pythontext.py
word = "café"data = word.encode()print(len(word), len(data), data)print(data.decode() == word)
textexample output
4 5 b'caf\xc3\xa9'True
TaskMethod
Split on a separator, join a lists.split(","), ", ".join(items)
Trim whitespaces.strip(), s.lstrip(), s.rstrip()
Replace a substrings.replace("old", "new")
Find a position, count occurrencess.find("x"), s.count("x")
Check the start and ends.startswith("http"), s.endswith(".py")
Change cases.lower(), s.upper(), s.title()
Check for digits onlys.isdigit()

Type checks and conversion

type(x) returns an object’s type, while isinstance(x, int) checks membership, subclasses included — use it in conditions. To convert a value, call the type like a function: int("42"), str(3.5), list("abc"). If a string does not look like an integer, int() raises ValueError.

In a condition, every value is converted to bool. False values are None, False, zero of any numeric type and empty collections: "", (), [], {}, set(), range(0). Everything else is true.

pythonconvert.py
for raw in ["42", "4.2", "", "abc"]:    if not raw:        print("empty string")        continue    try:        print(int(raw))    except ValueError:        print("not an integer:", raw)
textexample output
42not an integer: 4.2empty stringnot an integer: abc

Type hints

Type hints describe expected types: list[int], dict[str, float], int | None. The interpreter does not check them: a function annotated with int accepts a string too. Hints are checked by external tools — type checkers, linters and code editors.

pythonhints.py
def double(x: int) -> int:    return x * 2 print(double(21), double("ab"))
textexample output
42 abab

Section sources

the section is written from these pages

Functions, arguments and scope

A function is defined with the def keyword, takes arguments by position or by name and returns a value with return; without return, it returns None. Functions are ordinary objects: you can assign one to another name, pass it to another function or wrap it in a decorator.

pythongreet.py
def greet(name, greeting="Hello"):    """Return a greeting line."""    return f"{greeting}, {name}!" print(greet("Aziz"))print(greet("Malika", greeting="Salom"))
textexample output
Hello, Aziz!Salom, Malika!

The body runs when the function is called, but the def statement itself runs when the module loads. A default value is evaluated once, also when def runs, and then reused in every call.

pythonwrong
def add(item, items=[]):    items.append(item)    return items
pythonright
def add(item, items=None):    if items is None:        items = []    items.append(item)    return items

Positional and keyword parameters

In a signature, / marks off parameters that can only be passed by position, and * those that can only be passed by name. The author thus decides which parameter names belong to the interface, and a call like connect("db", 5432, 3), with a cryptic third number, becomes impossible.

pythonconnect.py
def connect(host, port=5432, /, *, timeout=10, ssl=True):    return f"{host}:{port} timeout={timeout} ssl={ssl}" print(connect("db.example.com", timeout=3))
textexample output
db.example.com:5432 timeout=3 ssl=True

*args, **kwargs and unpacking

*args collects extra positional arguments into a tuple, **kwargs collects extra keyword arguments into a dictionary. In a call, the stars do the reverse: * unpacks a sequence into positional arguments, ** unpacks a dictionary into keyword arguments.

pythonargs.py
def log(level, *args, **kwargs):    print(level, args, kwargs) log("INFO", "started", 42, user="admin")point = (3, 4)options = {"sep": " | "}print(*point, **options)
textexample output
INFO ('started', 42) {'user': 'admin'}3 | 4

Scopes: LEGB

A name is looked up in the nearest scope first, then further out: the function’s local names (Local), names of enclosing functions (Enclosing), the module’s global names (Global) and built-in names (Built-in). From the initials, this order is called LEGB. If the name is not found anywhere, NameError is raised.

Numbers show the lookup order; the first match wins.

Assigning to a name inside a function makes it local to the whole function, even if the same name exists outside. To assign to a global variable, declare it global; for a variable of an enclosing function, use nonlocal. Reading a local name before assignment raises UnboundLocalError.

pythoncounter.py
count = 0 def make_counter():    total = 0    def step():        nonlocal total        total += 1        return total    return step counter = make_counter()counter()print(counter(), count)
textexample output
2 0

Closures and lambda

A nested function that uses the outer function’s variables is a closure: it keeps access to them even after the outer function returns. That is how step remembers its total between calls. lambda creates a short anonymous function from one expression, typically as the key argument of sorted(), min() and max().

pythonsort_users.py
users = [("aziz", 31), ("malika", 25), ("timur", 40)]print(sorted(users, key=lambda user: user[1]))
textexample output
[('malika', 25), ('aziz', 31), ('timur', 40)]

Decorators

A decorator is a function that takes a function and returns a new one. @timer above def is equivalent to func = timer(func) after the definition. Use functools.wraps in the wrapper: it copies the original function’s name, docstring and other attributes; otherwise logs and the debugger will call the function wrapper.

pythontimer.py
import functoolsimport time def timer(func):    @functools.wraps(func)    def wrapper(*args, **kwargs):        start = time.perf_counter()        result = func(*args, **kwargs)        elapsed = time.perf_counter() - start        print(f"{func.__name__}: {elapsed:.3f} s")        return result    return wrapper @timerdef build_report(n):    return sum(range(n)) build_report(1_000_000)

functools also has ready-made tools: the @functools.cache decorator remembers results of calls with the same arguments, and functools.partial() creates a new function with some arguments already filled in.

Generators and yield

A function containing yield is a generator: calling it returns an iterator, and the body runs in pieces. On each request for the next value, the generator resumes where it stopped, keeping its local variables; when the body ends, iteration stops. Values are produced one at a time, on demand, so generators suit large files that should not be loaded into memory whole.

pythonnumbers.py
def read_numbers(path):    with open(path, encoding="utf-8") as f:        for line in f:            if line.strip():                yield int(line) total = sum(read_numbers("numbers.txt"))

Section sources

the section is written from these pages

Classes and objects

A class defines a new data type: attributes hold state, methods define behaviour. Calling the class creates an instance; __init__ sets its attributes, and self, the first parameter of a regular method, is the instance itself.

pythonaccounts.py
class Account:    currency = "UZS"     def __init__(self, owner, balance=0):        self.owner = owner        self.balance = balance     def deposit(self, amount):        if amount <= 0:            raise ValueError("amount must be positive")        self.balance += amount        return self.balance acc = Account("aziz")acc.deposit(500)print(acc.owner, acc.balance, acc.currency)
textexample output
aziz 500 UZS

An attribute declared in the class body (currency) is shared by all instances; one assigned via self belongs to each instance. If an instance and its class have attributes with the same name, the instance attribute wins.

Inheritance and super()

A subclass lists its base classes in parentheses and inherits their attributes and methods. An overriding method can call the base class version via super(). With multiple inheritance, the attribute lookup order is defined by the MRO (method resolution order), stored in the class attribute __mro__. Use isinstance() and issubclass() to check type membership.

pythonaccounts.py
class Savings(Account):    def __init__(self, owner, balance=0, rate=0.05):        super().__init__(owner, balance)        self.rate = rate     def add_interest(self):        return self.deposit(self.balance * self.rate) s = Savings("malika", 1000)print(s.add_interest(), isinstance(s, Account))print([cls.__name__ for cls in Savings.__mro__])
textexample output
1050.0 True['Savings', 'Account', 'object']

Special methods

Methods with double underscores on both sides (dunder methods) are called by the interpreter itself when an object is used with an operator or a built-in function. By implementing them, a class works with len(), for, == and with like built-in types.

MethodWhat calls it
__init__creating an instance: Account("aziz")
__repr__, __str__repr(obj) and REPL output; str(obj) and print(obj)
__eq__, __lt__a == b; a < b and sorted()
__hash__dictionary key, set element, hash(obj)
__len__, __bool__len(obj); the test in if obj:
__iter__, __contains__for x in obj; x in obj
__getitem__obj[key]
__call__calling the object: obj()
__enter__, __exit__with obj:
pythonplaylist.py
class Playlist:    def __init__(self, *songs):        self.songs = list(songs)     def __repr__(self):        return f"Playlist({len(self)} songs)"     def __len__(self):        return len(self.songs)     def __iter__(self):        return iter(self.songs)     def __eq__(self, other):        if not isinstance(other, Playlist):            return NotImplemented        return self.songs == other.songs p = Playlist("intro", "outro")print(p, len(p), list(p), p == Playlist("intro", "outro"))
textexample output
Playlist(2 songs) 2 ['intro', 'outro'] True

If a class defines __eq__ but not __hash__, its __hash__ becomes None: instances are unhashable and cannot go into a set or serve as dictionary keys.

property, classmethod and staticmethod

@property turns a method into a computed attribute read without parentheses; the @name.setter decorator defines what happens on assignment, such as validation. @classmethod receives the class instead of an instance, which is how alternative constructors are written. @staticmethod is a plain function living in the class namespace.

pythontemperature.py
class Temperature:    def __init__(self, celsius):        self.celsius = celsius     @property    def fahrenheit(self):        return self.celsius * 9 / 5 + 32     @classmethod    def from_fahrenheit(cls, value):        return cls((value - 32) * 5 / 9)     @staticmethod    def is_valid(celsius):        return celsius >= -273.15 t = Temperature.from_fahrenheit(212)print(t.celsius, t.fahrenheit, Temperature.is_valid(-300))
textexample output
100.0 212.0 False

Data classes: dataclasses

The @dataclass decorator generates __init__, __repr__ and __eq__ from the annotated fields. frozen=True makes the fields read-only after creation. A mutable default is set with field(default_factory=list): items: list = [] raises ValueError when the class is defined.

pythonmodels.py
from dataclasses import dataclass, field @dataclass(frozen=True)class Point:    x: float    y: float = 0.0 @dataclassclass Order:    id: int    items: list[str] = field(default_factory=list) order = Order(1)order.items.append("book")print(Point(1.5), order)
textexample output
Point(x=1.5, y=0.0) Order(id=1, items=['book'])

Private attributes by convention

Python has no private attributes. A name with one leading underscore (_cache) is internal by convention: outside code should not touch it, but access is not blocked. A name with two leading underscores (__token) is renamed inside the class to _ClassName__token; this prevents accidental clashes with subclass names, not access.

Section sources

the section is written from these pages

Exceptions and error handling

Python reports a runtime error with an exception: an object that interrupts execution and travels up the call stack until a try/except block catches it. If nothing catches it, the program exits and prints a traceback.

Reading a traceback

Read a traceback from the bottom up. The last line gives the exception class and message. Above it is the chain of calls from the entry point to the error: for each call, the file, line number and function, followed by the code being executed. Find the lowest call in your own code — the bug is usually there or in the data passed to it.

pythonserver.py
def parse_port(value):    return int(value) config = {"port": "80a"}parse_port(config["port"])
textexample output
Traceback (most recent call last):  File "/app/server.py", line 5, in <module>    parse_port(config["port"])    ~~~~~~~~~~^^^^^^^^^^^^^^^^  File "/app/server.py", line 2, in parse_port    return int(value)ValueError: invalid literal for int() with base 10: '80a'

try, except, else, finally

try holds code that may fail, except handles a specific exception class, subclasses included. The first matching except branch runs. else runs only if no exception occurred, and finally always runs, even after return or a new exception, so it is where resources are released.

pythonsettings.py
def read_port(path):    try:        with open(path, encoding="utf-8") as f:            port = int(f.read())    except FileNotFoundError:        return 8000    except ValueError as e:        raise SystemExit(f"bad port in {path}: {e}")    else:        return port    finally:        print("checked", path)

To catch several classes, list them as a tuple: except (ValueError, TypeError) as e:. Since Python 3.14, the parentheses are optional without as: except ValueError, TypeError:. The name after as is deleted when the except branch ends; to keep the exception, assign it to another variable.

Catch specific classes. A bare except: catches everything, including KeyboardInterrupt from Ctrl+C and SystemExit, and except Exception: with pass hides typos and bugs in the handler itself.

pythonwrong
try:    sync_orders()except:    pass
pythonright
import logging try:    sync_orders()except (ConnectionError, TimeoutError) as e:    logging.warning("sync failed, retry later: %s", e)

The exception hierarchy

All built-in exceptions are subclasses of BaseException. Besides Exception, its direct subclasses are SystemExit, KeyboardInterrupt, GeneratorExit and BaseExceptionGroup, which a plain except Exception does not catch. All other exceptions derive from Exception, and so should your own error classes.

ExceptionWhen it is raised
ValueErrorright type, wrong value: int("abc")
TypeErroroperation not supported for the type: "2" + 2
KeyErrorkey not in the dictionary
IndexErrorindex out of range
AttributeErrorobject has no such attribute
NameErrorname not defined
FileNotFoundErrorno such file or directory; subclass of OSError
ModuleNotFoundErrormodule not found; subclass of ImportError
ZeroDivisionErrordivision by zero
StopIterationiterator has no more items

raise, raise from and custom exceptions

raise raises an exception; a bare raise inside except re-raises the current one. raise NewError(...) from e records the original error as the cause: the traceback shows both, noting that the first directly caused the second. e.add_note("...") attaches an explanatory note that also appears in the traceback.

pythonconfig.py
class ConfigError(Exception):    """Invalid settings.""" def load_port(raw):    try:        return int(raw)    except ValueError as e:        raise ConfigError(f"port must be a number: {raw!r}") from e load_port("80a")
textexample output
Traceback (most recent call last):  ...ValueError: invalid literal for int() with base 10: '80a' The above exception was the direct cause of the following exception: Traceback (most recent call last):  ...ConfigError: port must be a number: '80a'

Exception groups and except*

When several independent operations fail at once, such as parallel tasks, their errors arrive as one ExceptionGroup object. An except* branch takes only exceptions of its type from the group; the rest pass to the next branch.

Propertyexceptexcept*
What it receivesone exceptionan ExceptionGroup subgroup of its type
Branches that runthe first matchall whose type is in the group
Without a typeallowed, catches allsyntax error
In one tryonly exceptonly except*
pythonbatch.py
errors = [ValueError("row 3"), OSError("disk")]try:    raise ExceptionGroup("batch", errors)except* ValueError as group:    print("bad data:", group.exceptions)except* OSError as group:    print("io:", group.exceptions)
textexample output
bad data: (ValueError('row 3'),)io: (OSError('disk'),)

with and context managers

with guarantees that a resource is released: the file is closed and the lock released even if an exception occurs in the block. The object after with is a context manager, with __enter__ and __exit__ methods. The easiest way to write one is the contextlib.contextmanager decorator, and contextlib.suppress silently ignores the given exception classes.

pythontimed.py
import timefrom contextlib import contextmanager, suppress @contextmanagerdef timed(label):    start = time.perf_counter()    try:        yield    finally:        elapsed = time.perf_counter() - start        print(f"{label}: {elapsed:.2f} s") with timed("sleep"):    time.sleep(0.1) with suppress(FileNotFoundError):    open("missing.txt").close()

Section sources

the section is written from these pages

Modules, packages and dependencies

A module is a .py file; its name without the extension is the name you import. A package is a directory of modules, usually with an __init__.py file. External dependencies are installed from PyPI into a virtual environment with python -m pip install and listed in pyproject.toml or requirements.txt.

pythonimports.py
import jsonimport datetime as dtfrom pathlib import Path print(json.dumps({"today": str(dt.date.today())}))print(Path.cwd().name)

import json binds the name json to the module object, from pathlib import Path binds just the name you need, and as picks another name. A module runs once, on first import; later imports take the ready object from the sys.modules cache. from module import * makes code hard to read; keep it for interactive mode.

Package layout

textproject tree
shop/├── pyproject.toml├── shop/│   ├── __init__.py│   ├── cli.py│   ├── models.py│   └── api/│       ├── __init__.py│       └── orders.py└── tests/    └── test_models.py

Inside a package, imports are absolute, from the package root (from shop.models import Order), or relative, with dots (from ..models import Order in shop/api/orders.py). A relative import relies on the current module’s package name. The program’s main module is named __main__ and has no package, so it uses absolute imports only.

Where Python looks for modules

Python first checks built-in modules, then searches the sys.path directories in order: the running script’s directory (or the current directory if there is no script), directories from PYTHONPATH, the standard library and the active environment’s site-packages. The first match wins, so a json.py next to your script shadows the standard library module.

bashterminal
python -c "import sys; print(*sys.path, sep='\n')"

An imported module’s bytecode is cached in __pycache__/models.cpython-315.pyc and rebuilt when the source changes. A module run directly from the command line is compiled every time and never cached.

Running a module: __name__ and -m

Every module has a __name__. When the file runs as a program, it is "__main__"; when imported, it is the module name. So start-up code goes under a condition and does not run when another module imports this one.

pythonshop/cli.py
import sys def main(argv):    print("args:", argv)    return 0 if __name__ == "__main__":    sys.exit(main(sys.argv[1:]))

Run a package module from the project root with -m: python -m shop.cli --dry-run. Python then finds the shop package via sys.path, and imports within the package work.

Lazy imports

Since Python 3.15, imports can be lazy: lazy import json does not load the module immediately but binds the name to a proxy object; the module loads on first use of the name. This defers modules that not every run of the program needs.

pythonPython 3.15
lazy import jsonimport sys print("json" in sys.modules)config = json.loads('{"debug": true}')print("json" in sys.modules, config)
textexample output
FalseTrue {'debug': True}

lazy is allowed only at module level: inside a function, class body or try/except/finally block it is a SyntaxError, as is lazy from module import *. A loading error, such as a misspelt module name, appears not at the import line but on first use of the name.

Project dependencies

Third-party packages are installed from PyPI into the active virtual environment. To reproduce the environment on another machine or server, record the dependencies in a file. For an application, a requirements.txt with exact versions from pip freeze is enough.

bashin an active .venv
python -m pip install requestspython -m pip freeze > requirements.txtpython -m pip install -r requirements.txt

For a package or a new project, metadata and dependencies go in pyproject.toml: the [build-system] table names the build tool, [project] holds the name, version, supported Python versions and dependencies, and [project.optional-dependencies] lists optional groups. Build tools, package managers and linters read this file.

tomlpyproject.toml
[build-system]requires = ["setuptools >= 77.0.3"]build-backend = "setuptools.build_meta" [project]name = "shop"version = "0.1.0"requires-python = ">=3.13"dependencies = [    "httpx",    "rich>=14",] [project.optional-dependencies]dev = ["pytest"]

Section sources

the section is written from these pages

asyncio, threads and processes

Python offers three tools for concurrency: asyncio for many network operations in one thread, threads for blocking I/O, and processes for computation on several cores. In the standard CPython build only one thread runs Python code at a time, so threads do not speed up computation.

Which to choose

TaskToolWhy
Many network requests and connectionsasynciotasks switch at await while waiting for a response
Blocking I/O: files, libraries without asyncThreadPoolExecutor, asyncio.to_thread()a thread waits without blocking the others
Computation on all coresProcessPoolExecutoreach process has its own interpreter and GIL
Computation in one process, since Python 3.14InterpreterPoolExecutoreach thread has its own isolated interpreter
Threads that compute in parallelfree-threaded buildno GIL: threads run code simultaneously

asyncio: async and await

async def defines a coroutine: calling it runs nothing and just returns a coroutine object. Coroutines are run by the event loop: asyncio.run() starts the entry point, and inside a coroutine await waits for another coroutine’s result. While a task awaits a network response or a timer, the event loop runs other tasks.

Tasks switch only at await points. A blocking call — time.sleep(), a synchronous HTTP client, a long computation loop — never yields control, and all other tasks stall meanwhile.

The event loop switches tasks only at await points.
pythontasks.py
import asyncio async def fetch(name, delay):    await asyncio.sleep(delay)    return f"{name}: {delay} s" async def main():    jobs = [("a", 1), ("b", 2), ("c", 1)]    async with asyncio.TaskGroup() as tg:        tasks = [tg.create_task(fetch(*job)) for job in jobs]    print([t.result() for t in tasks]) asyncio.run(main())
textexample output
['a: 1 s', 'b: 2 s', 'c: 1 s']

The three tasks finish in 2 seconds, not 4. asyncio.TaskGroup (since Python 3.11) starts tasks and waits for all of them when the async with block exits. If one task fails, the rest are cancelled and the errors arrive together as an ExceptionGroup. Since Python 3.15, tg.cancel() ends the group early without an exception.

Timeouts and cancellation

asyncio.timeout() cancels the current task when time runs out and turns the cancellation into TimeoutError, caught outside the async with block.

pythonreplaces main() in tasks.py
async def main():    try:        async with asyncio.timeout(5):            await fetch("slow", 10)    except TimeoutError:        print("gave up after 5 s")

Threads for blocking code

From a coroutine, call a blocking function with await asyncio.to_thread(func, ...): it runs in a separate thread while the event loop continues. Outside asyncio, ThreadPoolExecutor from concurrent.futures does the same: the pool distributes calls among threads and collects the results.

pythondownload.py
import urllib.requestfrom concurrent.futures import ThreadPoolExecutor URLS = [    "https://www.python.org/",    "https://pypi.org/",    "https://example.com/",] def size(url):    with urllib.request.urlopen(url, timeout=10) as resp:        return url, len(resp.read()) with ThreadPoolExecutor(max_workers=4) as pool:    for url, n in pool.map(size, URLS):        print(url, n)

Protect shared mutable data, like counter in the example, with a threading.Lock, which only one thread can hold at a time. The documentation advises against relying on the internal locks of built-in types (dict, list, set).

pythoncounter.py
import threading counter = 0lock = threading.Lock() def work():    global counter    for _ in range(100_000):        with lock:            counter += 1 threads = [threading.Thread(target=work) for _ in range(4)]for t in threads:    t.start()for t in threads:    t.join()print(counter)
textexample output
400000

Processes for computation

For heavy computation, use ProcessPoolExecutor: each process is a separate interpreter with its own GIL, so work runs on several cores. Functions and arguments reach the processes via pickle, so the function must be defined at the top level of a module, not in the REPL or as a lambda. The main module must import without side effects, so start-up code goes under if __name__ == "__main__":.

pythonprimes.py
from concurrent.futures import ProcessPoolExecutor def is_prime(n):    if n < 2:        return False    return all(n % d for d in range(2, int(n ** 0.5) + 1)) if __name__ == "__main__":    numbers = [999_983, 1_000_001, 1_000_003]    with ProcessPoolExecutor() as pool:        print(list(pool.map(is_prime, numbers)))
textexample output
[True, False, True]

The GIL and the free-threaded build

In the standard CPython build, the global interpreter lock (GIL) lets only one thread at a time run bytecode. The free-threaded build (since Python 3.13) has no GIL, and threads run Python code in parallel; the official macOS and Windows installers can install it. A C extension not marked as compatible may re-enable the GIL, and Python warns about it.

bashterminal
python3 -VVpython3 -c "import sys; print(sys._is_gil_enabled())"

In a free-threaded build, python3 -VV output contains “free-threading build”, and sys._is_gil_enabled() shows whether the GIL is enabled at the moment. Single-threaded code runs slightly slower in such a build and uses more memory.

Section sources

the section is written from these pages

The standard library

The standard library is the set of modules shipped with Python: files and paths, JSON and CSV, dates and times, an HTTP client, command-line arguments, logging, running external programs. Before installing a package from PyPI, check whether the standard library already covers the task.

TaskModule
Paths, reading and writing filespathlib
Copying and moving files and directoriesshutil
Files matching *.pyglob, Path.glob()
JSON, CSV, XMLjson, csv, xml.etree.ElementTree
A database in a single filesqlite3
Dates and timesdatetime
Regular expressionsre
HTTP requests, sending emailurllib.request, smtplib
Command-line argumentsargparse
Program logslogging
Running external programssubprocess
Exact decimal arithmeticdecimal
Queue, sorted list, heapcollections.deque, bisect, heapq
Compression and archiveszlib, gzip, zipfile, tarfile
Measuring execution timetimeit

For testing, the standard library has unittest and doctest; in practice pytest is more common and has its own reference. Tables and data analysis are covered in the pandas reference.

Files and JSON with pathlib

Path joins path parts with the / operator and behaves the same on Linux, macOS and Windows. read_text() and write_text() open and close the file themselves, and mkdir(parents=True, exist_ok=True) creates a directory with its parents and does not fail if it exists. Specify the encoding explicitly.

pythonbuild_config.py
import jsonfrom pathlib import Path config_path = Path("config") / "settings.json"config = json.loads(config_path.read_text(encoding="utf-8"))config["debug"] = False out = Path("build")out.mkdir(parents=True, exist_ok=True)text = json.dumps(config, indent=2)(out / "settings.json").write_text(text, encoding="utf-8") for path in sorted(Path(".").glob("*.py")):    print(path.name, path.stat().st_size)

Command-line arguments: argparse

pythontop.py
import argparse parser = argparse.ArgumentParser(description="Show top lines")parser.add_argument("files", nargs="+")parser.add_argument("-n", "--lines", type=int, default=10)args = parser.parse_args()print(args.files, args.lines)
bashterminal
python top.py -n 5 access.log error.log
textexample output
['access.log', 'error.log'] 5

argparse parses positional arguments and flags, converts values to the required types and reports an error when arguments are invalid. Without it, arguments are plain strings in the sys.argv list.

Program logs: logging

pythonapp.py
import logging logger = logging.getLogger(__name__) def main():    logging.basicConfig(        level=logging.INFO,        format="%(asctime)s %(levelname)s %(name)s: %(message)s",    )    logger.info("started")    logger.warning("disk usage %d%%", 91) if __name__ == "__main__":    main()

Each module creates its own logger with logging.getLogger(__name__); logging is configured — level, format, destination — once at start-up with basicConfig(). Without configuration, DEBUG and INFO messages are hidden, and the rest go to standard error.

External programs: subprocess

pythonlast_commit.py
import subprocess result = subprocess.run(    ["git", "log", "-1", "--format=%h %s"],    capture_output=True,    text=True,    check=True,)print(result.stdout.strip())

subprocess.run() starts a program, waits for it to finish and returns a CompletedProcess with the return code and output. Pass the command as a list of arguments: without a shell, spaces and quotes in file names cannot break it. check=True turns a non-zero return code into a CalledProcessError, and timeout limits the run time.

Section sources

the section is written from these pages

Common errors and troubleshooting

Start with three questions: which interpreter is running, whether the right virtual environment is active and what the last line of the traceback says. A common cause of installation problems is a package installed into one Python and a program run by another.

Diagnostic steps

  1. Find out which interpreter runs: sys.executable is its path.
  2. Check the environment: inside a venv, sys.prefix points to the environment directory and differs from sys.base_prefix.
  3. See where modules are searched: the running script’s directory comes first in sys.path.
  4. Read the traceback from the bottom up: the exception class and message are on the last line.
bashterminal
python -c "import sys; print(sys.executable)"python -c "import sys; print(sys.prefix != sys.base_prefix)"python -c "import sys; print(*sys.path, sep='\n')"

ModuleNotFoundError

Cause: the module is in none of the sys.path directories of the interpreter running the program. Usually the package was installed into another environment, or the environment is not activated; sometimes the module name is misspelt.

bashcheck
python -c "import sys; print(sys.prefix)"ls .venv/bin/python
bashfix
source .venv/bin/activatepython -m pip install requests

pip refuses to install into the system Python

Cause: the distribution has marked its Python with an EXTERNALLY-MANAGED file (PEP 668) so that pip does not break packages managed by apt or dnf. pip reports an externally managed environment and suggests a virtual one. The protection applies only outside a venv, when sys.prefix equals sys.base_prefix, so the check prints True.

bashcheck
python3 -c "import sys; print(sys.prefix == sys.base_prefix)"
bashfix
python3 -m venv .venv.venv/bin/python -m pip install requests

If Debian or Ubuntu cannot create the environment itself, install the python3-full distribution package. pip’s --break-system-packages flag disables the protection and can break system programs; do not use it on a server.

IndentationError and TabError

Cause: the indentation does not match the block nesting, or a file mixes tabs and spaces. TabError is a subclass of IndentationError, which is a subclass of SyntaxError, so the program does not start at all.

  • Make the editor show whitespace characters and look for tabs in the indentation
  • Set the editor to insert 4 spaces on Tab
  • Replace tabs with spaces throughout the file

TypeError with NoneType

Cause: None appeared where a list, dictionary or string was expected. Usually it comes from a function without return or a method that changes an object in place and returns None: items = items.sort() leaves None in items.

pythoncheck
print(repr(result), type(result))
pythonfix
items.sort()ordered = sorted(items)

UnicodeDecodeError

Cause: the file is read with a different encoding from the one it was written in. Since Python 3.15, open() without encoding reads UTF-8 on all systems, so old files in cp1251 and other Windows encodings fail with this error even where they used to open.

pythoncheck: raw bytes
with open("report.csv", "rb") as f:    print(f.read(60))
pythonfix
with open("report.csv", encoding="cp1251") as f:    text = f.read()

RecursionError

Cause: a function calls itself without an exit condition, or too deeply, and the call depth exceeds the interpreter limit, sys.getrecursionlimit().

bashcheck
python -c "import sys; print(sys.getrecursionlimit())"
  • Check the recursion’s exit condition and that each call moves towards it
  • Rewrite deep tree and graph traversals as a loop with an explicit stack

ImportError from a circular import

Cause: two modules import each other, and from a import name runs while module a is only partly loaded, before the name exists. If the cycle passes through a lazy import (since Python 3.15), the exception is ImportCycleError, a subclass of ImportError.

  • Move the shared code into a third module that both import
  • Import the whole module (import a) and use a.name at call time
  • Move the import into the function that uses it

Your file shadows a standard library module

Cause: the running script’s directory comes first in sys.path, so your json.py, random.py or email.py is loaded instead of the module with that name. The symptom is an AttributeError or ImportError for a name that the module’s documentation definitely lists.

bashcheck
python -c "import json; print(json.__file__)"
  • Rename your file, for example to json_tools.py
  • Do not name your modules after standard library modules or installed packages

Other symptoms

SymptomCauseWhat to do
KeyboardInterrupt in the tracebackthe program was stopped with Ctrl+Cnothing; put resource clean-up in finally
KeyError with a key nameno such key in the dictionarycheck the spelling; config.get("port", 8000) returns a default
FileNotFoundErrorno file at the given pathcheck the path and the current directory: os.getcwd()
PermissionErrorthe process lacks permissions for the file or directorycheck the file’s owner and permissions
NameError or UnboundLocalErrorthe name is undefined or read before assignment in a functioncheck for typos and a missing import; pass the value as an argument
ValueError from int()the string does not look like a numberclean the input with strip() and handle ValueError
StopIteration outside a loopnext() called on an exhausted iteratorpass a default: next(it, None)

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Python 3.15 (CPython). The latest release, 3.15.2, came out on 25 October 2026. A new branch is released once a year, in October; it gets bug fixes for two years, then security fixes only, and reaches end of life five years after release.

BranchStatusLatest releaseSupported until
3.15bug fixes3.15.2, 25 October 2026October 2031
3.14bug fixes3.14.10, 25 October 2026October 2030
3.13security fixes only3.13.18, 25 October 2026October 2029
3.12security fixes only3.12.16, 25 October 2026October 2028
3.10end of life3.10.22, 1 October 20261 October 2026

The 3.11 branch also gets security fixes only, until October 2027. Security-only branches ship releases as source code, without new installers.

What changed in 3.15

  • Modules: lazy imports — lazy import json defers loading the module until the name is first used.
  • Types: a built-in immutable dictionary, frozendict, and the sentinel type for unique marker values.
  • Syntax: unpacking in comprehensions — [*row for row in rows] and {**d for d in dicts}.
  • Types: UTF-8 is now the default encoding for open() and other I/O, whatever the system settings; an explicit encoding is still more reliable.
  • Standard library: the profiling package brings the profilers together; the new profiling.sampling (Tachyon) attaches to a running process by PID without restarting it.
  • asyncio: TaskGroup.cancel() ends a task group early without an exception.
  • Exceptions: AttributeError suggestions are more accurate — for [1, 2].push(3), Python suggests .append.
  • Installation: the official macOS builds also install the free-threaded interpreter by default, and the 64-bit Windows builds use the faster tail-calling interpreter.

Deprecated and removed

  • The profile module is deprecated and will be removed in 3.17 — use profiling.tracing.
  • re.match() is soft deprecated: there are no plans to remove it, but use re.prefixmatch() in new code.
  • The __version__, version and VERSION attributes of standard library modules (json, logging, re, csv and others) will be removed in 3.20 — get the Python version from sys.version_info.
  • The asyncio policy system (asyncio.set_event_loop_policy() and related functions) will be removed in 3.16 — choose the event loop with asyncio.run(main(), loop_factory=...).
  • Bitwise inversion of booleans, ~True and ~False, has been deprecated since 3.12 and is scheduled for removal in 3.16 — use not x for logical negation.
  • Removed: the sre_compile, sre_constants and sre_parse modules, the http.server.CGIHTTPRequestHandler class and the --cgi flag of python -m http.server.
  • The __cached__ module attribute is no longer set — use __spec__.cached.

Security fixes

IdentifierAffected componentFixed in
CVE-2026-115557ssl: certificate chains with compromised eMudhra intermediate CAs3.15.2
CVE-2026-114583tarfile.tar_filter(): a link pointing to the extraction directory itself3.15.2
CVE-2026-12345tempfile.TemporaryDirectory: a race during clean-up could delete files outside the temporary directory3.15.0
CVE-2026-19445ssl: a crash when sni_callback switches the connection to another SSLContext3.15.0
CVE-2026-15806urllib.request: the HTTPPasswordMgr password for HTTPS was also sent over HTTP3.15.0
CVE-2026-3219the pip installed by ensurepip; upgraded to 26.13.15.0
CVE-2026-45186the bundled libexpat library; upgraded to 2.8.13.15.0
CVE-2026-4224xml.parsers.expat: a crash on deeply nested DTD content models3.15.0
CVE-2026-3644http.cookies.Morsel: control characters in cookies3.15.0
CVE-2026-2297SourcelessFileLoader opened .pyc files bypassing io.open_code()3.15.0

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 2 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Python” topic
14 sections
Another reference · Backend

Django

Verified 1 Nov
All references · 61