151 terms across 10 categories
del is an object's finaliser. CPython may call it when the last reference disappears. It is unreliable across implementations and interacts badly with cycles. Prefer with and weakref.finalize.
A shallow copy duplicates a container but reuses the element objects. A deep copy walks the graph and clones everything. Assignment (b = a) copies no objects at all.
The cyclic garbage collector finds groups of objects that reference each other and are otherwise unreachable, so reference counts never hit zero. CPython runs it in generations on allocation thresholds.
Garbage collection reclaims objects that the program can no longer reach. CPython combines reference counting for the common case with a cyclic collector for objects that point at each other.
Interning reuses one object for equal values so identity matches equality. CPython interns small integers and some strings; sys.intern does it on demand.
A memoryview is a window onto an object's raw buffer. It lets you slice and interpret bytes without copying, as long as the object supports the buffer protocol.
A mutable object can change in place: lists, dicts, sets, bytearrays. An immutable object's value is fixed after creation: ints, floats, strings, bytes, tuples, frozensets. Names can still be rebound to a different object.
Every object has an identity that does not change during its lifetime. id(obj) returns that identity as an integer. is tests whether two names refer to the same object.
Reference counting is CPython's first memory manager: each object stores how many names and containers point at it. When the count hits zero, the object is deallocated immediately.
init is the instance initialiser. After new creates the object, init(self, ...) fills in its attributes. It is the method you write for almost every class that holds state.
new is the real constructor: a static method that allocates (or reuses) an instance and returns it. init then initialises that instance. Most classes never override new.
repr is the unambiguous developer representation of an object, used by the REPL and repr(). str is the readable user representation, used by print and str(). If str is missing, Python falls back to repr.
slots is a class attribute that names the instance fields the class will allow. Instances then skip dict and store those fields in a compact layout, which saves memory and blocks accidental attributes.
self is the conventional name of the first parameter of an instance method: the instance the method was called on. Python passes it automatically when you write order.total().
@property turns a method into something callers read like a plain attribute. It lets you add validation or computation behind order.qty later, without changing a single line of code that already uses it.
An abstract base class (ABC) is a class that names methods subclasses must implement and that you cannot instantiate until they do. abc.ABC and @abstractmethod are the standard-library tools.
A class method receives the class as its first argument instead of an instance. It is the standard way to write alternative constructors and any behaviour that belongs to the class as a whole rather than to one object.
A class is a blueprint for objects: it names a type, holds methods, and describes the attributes each instance will carry. class Order: creates that type; calling Order(...) creates an instance.
A dataclass is a class that gets init, repr, and optional comparison methods generated from type-annotated fields. @dataclass is the decorator that writes that boilerplate.
A descriptor is an object that customises attribute access by implementing get, set, or delete. Properties, methods, classmethod, and staticmethod are all descriptors.
Dunder methods are names with double underscores on both sides, such as init and len. Python calls them for language operations: construction, arithmetic, iteration, formatting, and context management.
Encapsulation is keeping an object's data and the rules that change it in one place, and exposing a small public surface. Python does this by convention and properties, not by a compiler-enforced private.
Inheritance lets a class reuse and override the behaviour of another class. class PriorityOrder(Order): is a subclass: it is an Order, plus whatever it adds or replaces.
A metaclass is the class of a class. It decides how a class object is created from a class statement. The default metaclass is type. You write one only when you must change that process.
A mixin is a class written to be inherited alongside a real base, providing a slice of behaviour and no independent identity. You instantiate the combined class, not the mixin.
The method resolution order (MRO) is the linear sequence of classes Python searches when looking up an attribute on a class or instance. Class.mro shows it. super() walks it.
Multiple inheritance is a class that lists more than one base: class View(AuthMixin, TemplateView):. Python flattens the bases into a single method resolution order so each attribute has one winner.
An object is a concrete value in memory: it has an identity, a type, and data. Numbers, strings, lists, functions, and class instances are all objects. There are no unboxed primitives in Python.
Polymorphism is using one call site with many types: shape.area() works for a circle or a rectangle because each type supplies its own area. In Python this is usually duck typing plus inheritance, not a compiler-checked interface.
A static method is an ordinary function that lives inside a class body. It receives no self and no cls, so it cannot touch instance or class state; it is grouped with the class only for readability.
name is a module's dotted import name. When you run a file as a program, name is "main". The if name == "main": guard runs a block only in that case, not when the file is imported.
args collects any extra positional arguments into a tuple, and *kwargs collects any extra keyword arguments into a dictionary. Together they let one function accept a variable number of inputs.
A for or while loop may have an else clause. The else block runs when the loop finishes normally, and is skipped if the loop left through break.
global tells a function that an assignment should update a module-level name. nonlocal tells a nested function that an assignment should update a name in an enclosing function. Without them, assignment creates a local.
import loads a module, caches it, and binds names in the current namespace so you can use its functions, classes, and constants. from ... import ... binds selected names directly.
lambda creates a small anonymous function from a single expression. It is a shorthand for a def you would otherwise write only to pass it as a callback.
match / case is structural pattern matching: you compare a value against shapes, bind the pieces that match, and run the first successful case. It is not a C-style switch on integers.
pathlib is the standard-library object-oriented API for filesystem paths. A Path joins parts, inspects names, and reads or writes files without string concatenation.
pip is the standard tool that installs Python packages from PyPI or a local project into the current interpreter. Packaging is the work of declaring dependencies and shipping your own code as an installable distribution.
Protocol describes a type by the methods and attributes it has, not by its class tree. TypedDict describes a dictionary by its keys and the type of each value. Both live in typing and help checkers without changing runtime behaviour.
with runs a block of code while a resource is checked out, and guarantees the matching cleanup step runs when the block ends — whether it ends normally, by a return, or by an exception.
yield hands one value out of a function and pauses it, keeping its local variables alive until someone asks for the next value. yield from delegates to another generator, forwarding values out and inputs in, and evaluates to that generator's return value.
str is a sequence of Unicode characters. bytes is a sequence of integers in 0..255. You convert between them with an encoding such as UTF-8; you cannot concatenate them.
Conditionals choose which block of code runs by testing a condition. Python uses if, elif, and else, plus a one-line conditional expression when you need a value rather than a statement.
A context manager is an object that sets something up, yields it to a with block, and tears it down afterwards. Files, locks, and database connections are context managers so cleanup cannot be forgotten.
CPython is the reference implementation of the Python language, written in C. It is the interpreter almost everyone means when they say "Python", and its internal design explains a great deal of the behaviour learners mistake for language rules.
A data type is the kind of value a name refers to: integer, string, list, function, and so on. In Python every value is an object with a type, and that type decides which operations are legal.
A decorator is a function that takes a function and returns a replacement for it. The @name line above a definition applies one, letting you add behaviour such as timing, caching, or access checks without editing the function body.
A default argument is the value a parameter takes when the caller omits it. Python evaluates each default once, when the def statement runs, and reuses that same object on every later call.
Dict and set comprehensions build a new dictionary or set from an iterable using {...} syntax. A dict comprehension writes key: value. A set comprehension writes a single expression.
Duck typing means Python cares about what an object can do, not what class it came from. If it has the methods your code calls, it is an acceptable argument, regardless of its type or ancestry.
In Python, types belong to objects rather than to names, and every type check happens while the program runs. Nothing stops you from passing the wrong kind of value; you find out when an operation is attempted on it.
An exception group is a single exception that carries several independent errors at once. except* handles one type out of the group and leaves the rest for later clauses. The feature arrived in Python 3.11.
An exception is an object that interrupts normal control flow when something goes wrong. You raise one with raise and handle it with try / except / else / finally.
An f-string is a string literal prefixed with f or F that interpolates expressions inside {...}. It is the usual way to build a readable string from variables in modern Python.
File I/O is reading and writing bytes or text on disk. open (or Path.open) returns a file object; with closes it. Mode and encoding decide whether you see str or bytes.
Functions are first-class values in Python: you can assign them, store them, pass them as arguments, and return them from other functions. A function that takes or returns a function is called higher-order.
A function is a named, reusable block of code you call with arguments. def creates one, parameters receive the values, and return sends a result back to the caller.
A generator produces values one at a time, on demand, instead of building the whole sequence up front. Any function containing yield becomes a generator function, and calling it returns a paused object that computes the next value only when asked.
Python is compiled and interpreted. Your source is first compiled into bytecode, a compact instruction list for a virtual stack machine, and the interpreter then executes those instructions one at a time.
The iterable protocol is how Python decides that an object can be walked by for, unpacked, or passed to list(). An iterable implements iter (or the older getitem sequence protocol) and returns a fresh iterator.
An iterator is an object that produces values one at a time and remembers its place. You get the next value with next(it), and when the values run out it raises StopIteration.
A list comprehension builds a new list by evaluating an expression for each item in an iterable, optionally skipping items with if. It replaces a short for loop that only appends.
A loop repeats a block of code. for walks an iterable one item at a time. while repeats as long as a condition stays true. Both can use break, continue, and an else clause that runs when the loop was not broken.
A module is a single .py file loaded as a namespace. A package is a directory of modules, typically with an init.py, that lets you group related files under one dotted name.
Binding is the act of attaching a name to an object inside a namespace. Assignment is only one of about a dozen operations that bind, and Python decides which namespace a name belongs to when it compiles your code, not when it runs it.
Operators are the symbols that combine or compare values: +, -, *, /, ==, is, and, and the rest. Each one is a method call on the operands' types, which is why + concatenates strings and adds numbers.
Scope is the region of a program where a name is visible. Python looks up names in four layers, remembered as LEGB: Local, Enclosing, Global, Built-in.
Truthiness is how Python decides whether a value counts as true or false in an if, while, or and/or expression. Many objects are usable as conditions without an explicit comparison to True.
Type hints are optional annotations that describe the intended types of parameters, returns, and variables. They document the contract for humans and checkers; the interpreter does not enforce them at runtime.
In Python a variable is a name bound to an object, not a box that holds a value. Assignment points a name at an object; it never copies the object.
A virtual environment is a private Python install plus a private site-packages directory for one project. It keeps that project's dependencies from colliding with other projects or with the system interpreter.
The walrus operator := assigns a value to a name and yields that value, so you can bind and test in one expression. It was added in Python 3.8 and is named for the := shape.
async def declares a coroutine function. await pauses it until an awaitable finishes and returns that result. Together they are the syntax of asyncio, not a second thread.
asyncio is the standard library for concurrent I/O on a single thread using an event loop, coroutines, and tasks. It overlaps waiting, not CPU-bound Python.
concurrent.futures is a high-level interface for running callables in a pool of threads or processes. You submit work, get back a Future, and collect results as they finish.
queue.Queue is a thread-safe FIFO used to pass work between producer and consumer threads. multiprocessing.Queue does the same across processes. asyncio.Queue does it among tasks.
A deadlock is a standstill where each participant waits for a resource another participant holds, so nobody can move. In Python it is usually two locks taken in opposite order, or a thread joining itself.
The event loop is the asyncio scheduler: it runs ready callbacks and coroutines, waits for I/O, fires timers, and resumes tasks when their futures complete.
The Global Interpreter Lock (GIL) is a mutex in CPython that only one thread at a time may hold while executing Python bytecode. Threads overlap I/O; they do not run CPU-bound Python in parallel on multiple cores.
A lock is a mutex that only one thread (or task) may hold at a time. You use it so a read-modify-write on shared state cannot interleave with another.
multiprocessing runs code in child processes, each with its own Python interpreter and GIL. It is the standard way to use multiple cores for CPU-bound Python.
A race condition is a bug whose result depends on the unpredictable timing of threads or tasks. Two interleavings that should be equivalent are not, so the program is sometimes wrong.
The threading module starts OS threads that share the same process and memory. Use it for concurrent I/O. The GIL keeps CPU-bound Python from running in parallel.
bisect is the standard-library binary search on a sorted list. It finds an insertion point in O(log n) time and can keep a list ordered as you insert.
Backtracking is a depth-first search that builds a candidate incrementally, abandons it as soon as it cannot lead to a valid solution, and undoes the last choice before trying the next.
Breadth-first search (BFS) visits a graph level by level: all neighbours of the start, then their neighbours, and so on. A queue holds the frontier. It finds shortest paths in unweighted graphs.
Binary search finds a target in a sorted sequence by repeatedly discarding half of the remaining range. It runs in O(log n) comparisons and needs random access.
Depth-first search (DFS) walks a graph by going as deep as possible along one path before backtracking. It is implemented with recursion or an explicit stack, and it is the usual engine for backtracking and cycle detection.
Dynamic programming (DP) solves a problem by combining answers to overlapping subproblems, storing each subproblem's result once. Memoised recursion and bottom-up tables are the two usual forms.
A greedy algorithm builds a solution by always taking the choice that looks best right now. It is fast when a proof says those local choices produce a global optimum, and wrong when they do not.
Hashing for lookup means putting keys in a dict or set so average membership and retrieval are O(1) instead of scanning a list. It is the standard way to turn nested loops into one pass.
Heap algorithms use a binary heap to keep a running extreme (minimum or maximum) in O(log n) per update. In Python they are written with heapq on a list.
A prefix-sum array stores the running total up to each index so any range sum can be answered in O(1) after O(n) setup. The same idea works for counts, xors, and other invertible aggregates.
Recursion is a function calling itself on a smaller input until it hits a base case. Trees, divide-and-conquer, and backtracking are naturally recursive; Python's call stack is finite.
A sliding window maintains a contiguous slice of a sequence as the slice moves, adding on one side and dropping on the other. It turns many O(n²) subarray problems into O(n).
Sorting puts a sequence into order. Python's sort and sorted use Timsort, a stable O(n log n) algorithm. You control the order with key and reverse.
Space complexity describes how extra memory an algorithm needs as the input grows. Auxiliary space excludes the input itself; total space includes it.
Time complexity describes how the number of steps in an algorithm grows as the input gets larger. Big O names the dominant term: O(1), O(n), O(n log n), O(n²), and so on.
Two pointers is a technique that walks a sequence with a pair of indices instead of nested loops. The pointers move toward each other, or in the same direction, and each item is processed a constant number of times.
Union-find (disjoint-set union) keeps a partition of elements into groups. find reports which group an element belongs to; union merges two groups. With path compression and union by rank, both operations are nearly O(1).
bytes is an immutable sequence of integers in 0..255. bytearray is the mutable counterpart. Both represent raw binary data, not Unicode text.
collections.deque is a double-ended queue: a sequence you can append and pop from either end in O(1) time. It is the right structure for queues, sliding windows, and BFS.
collections.Counter is a dict subclass that counts hashable items. It is a bag or multiset: keys are items, values are counts, and missing keys read as zero.
collections.defaultdict is a dict that calls a factory for missing keys instead of raising KeyError. defaultdict(list) is the usual way to group items.
heapq is the standard-library heap: a min-heap stored in a list. heappush and heappop keep the smallest item at index 0 in O(log n) time.
collections.namedtuple builds a tuple subclass with named fields. You get index access, attribute access, unpacking, and a readable repr without writing a class by hand.
A dictionary maps hashable keys to values and finds a key in roughly constant time, regardless of how many entries it holds. Since Python 3.7 it also preserves the order in which keys were first inserted.
A frozenset is an immutable set. It supports every read-only set operation and nothing that would change its contents, which makes it hashable and therefore usable as a dictionary key or as a member of another set.
A graph as a dict is an adjacency list stored in a dictionary: each key is a node, each value is the collection of neighbours. It is the usual Python representation for BFS, DFS, and shortest paths.
A list is Python's built-in mutable sequence: an ordered, resizable collection of references to objects, indexed from zero. It is the default container you reach for when order matters and the size is not known in advance.
A set is an unordered collection of unique, hashable values. It answers "is this in here?" in roughly constant time and silently drops duplicates on insertion.
A stack is last-in, first-out. A queue is first-in, first-out. In Python a list is a stack; collections.deque is a queue (and a stack). The queue module adds thread-safe variants.
A Python string is an immutable sequence of Unicode code points. Every operation that looks like editing a string in fact builds a new one, which is why text-heavy loops need str.join rather than repeated concatenation.
A tuple is an immutable ordered sequence. Once built, you cannot add, remove, or replace its elements, which makes a tuple of immutable values usable as a dictionary key or a set member.
unittest.mock is the standard-library toolkit for test doubles: Mock, MagicMock, AsyncMock, patch, and sentinel. It records calls and can replace names for the duration of a test.
Coverage measures which lines (and optionally branches) ran during the test suite. coverage.py is the usual tool; pytest-cov wires it to pytest. A percentage is a hint, not a proof of quality.
A fixture is reusable test setup (and teardown) that pytest injects into a test by parameter name. @pytest.fixture defines one; def test_ok(db): requests it.
Mocking replaces a real collaborator with a stand-in so a test can run without a network, a clock, or a disk, and so you can assert that a call happened.
@pytest.mark.parametrize runs one test function many times with different arguments. Each tuple is a case with its own name in the report.
pytest is the usual third-party test runner for Python. Tests are plain functions that use assert, plus fixtures for setup and plugins for almost everything else.
unittest is the standard-library xUnit framework: you subclass TestCase, write methods named test_*, and assert with self.assertEqual and friends. python -m unittest discovers and runs them.
An adapter translates one object's interface into another that a caller already expects. It lets you keep a third-party API out of the rest of the program.
The context manager pattern is acquire/release as an object you use with with. Setup runs on entry, teardown on exit, including when the block raises.
The decorator pattern wraps an object with another object that implements the same interface and adds behaviour before or after delegating. It is composition, and it is related to — but not the same as — Python @ function decorators.
Dependency injection means a function or object receives its collaborators as arguments instead of importing and constructing them itself. Tests pass fakes; production passes the real clients.
A facade is a single, simpler object that fronts a cluster of collaborators. Callers use the facade; they do not wire the subsystems themselves.
A factory is a function or method that creates objects so callers do not call a concrete class themselves. In Python that is often a @classmethod alternative constructor or a small function with if/match.
Observer is a publish/subscribe split: a subject keeps a list of callables and notifies them when its state changes. Listeners do not poll; they are called.
A repository is an object that pretends to be an in-memory collection while loading and saving domain objects behind the scenes. Callers ask for an Order, not a SQL row.
A singleton is a type that has at most one instance. In Python a module is already a singleton; a class-based singleton is for when you need an instance API or lazy setup.
Strategy replaces a hard-coded algorithm with a pluggable callable or object. The context calls strategy.execute(...) and does not know which variant it is.
A connection pool keeps a set of open database connections and lends them out, so each request does not pay for a new TCP handshake, TLS, and authentication.
The DB-API (PEP 249) is the common interface for Python database drivers: connect, cursor, execute, fetchone/fetchall, and commit/rollback. sqlite3, psycopg, and mysqlclient all speak it.
Isolation levels decide what one transaction can see of another's uncommitted or concurrent work. From weakest to strongest: Read Uncommitted, Read Committed, Repeatable Read, Serializable.
A migration is a versioned, repeatable change to a database schema (and sometimes to data). Alembic and Django migrations are the two common Python tools. create_all is not a migration strategy.
An object-relational mapper (ORM) maps classes and instances to tables and rows so you work with Order objects instead of SELECT strings. SQLAlchemy and the Django ORM are the two you will meet first.
Raw SQL is a query you write as a string and send through a cursor, engine.execute, or Model.objects.raw. You own the SQL, the parameters, and the mapping back to Python.
SQL injection is the bug where untrusted text is concatenated into a query and then executed as SQL. A username of '; drop table orders;-- becomes part of the program. Bound parameters prevent it.
SQLAlchemy is the main Python SQL toolkit: a Core expression language that compiles to SQL, and an optional ORM that maps classes to tables. You choose how much of it to use.
A transaction is a group of SQL statements that commit as a unit or roll back as a unit. Either the charge and the stock decrement both happen, or neither does.
Cross-Origin Resource Sharing (CORS) is the browser rule that lets a page on one origin call an API on another. The server opts in with Access-Control-Allow-* headers. Python frameworks expose this as middleware.
A Django view is a callable that takes a request and returns a response. Function views are def view(request):. Class-based views put HTTP methods on a class and are wired with .as_view().
FastAPI is an ASGI framework for HTTP APIs. You declare path operations with type hints; Pydantic validates bodies; OpenAPI docs are generated. Async and sync views are both supported.
Flask is a lightweight WSGI web framework. You decorate functions with routes, return strings or JSON, and add extensions for the rest. It stays out of your project layout until you invite it in.
HTTP is the request/response protocol of the web: a client sends a method, URL, headers, and optional body; the server replies with a status, headers, and a body. Python talks HTTP through urllib, http.client, Requests, and ASGI/WSGI apps.
JSON is a text format for objects, arrays, strings, numbers, booleans, and null. Python's json module converts between that text and dicts, lists, strs, ints, floats, bools, and None.
Requests is the widely used third-party HTTP client for Python. requests.get(url) returns a Response with status, headers, and body helpers. It is synchronous and blocking.
REST is an architectural style for HTTP APIs: resources have URLs, verbs are HTTP methods, and representations (usually JSON) are transferred statelessly. Most "REST" APIs are pragmatic resource-oriented HTTP, not a dissertation on hypermedia.
An HTTP status code is the three-digit number that classifies a response: 2xx succeeded, 3xx redirect, 4xx client error, 5xx server error. Clients, proxies, and caches branch on it before they read the body.
WSGI is the synchronous Python web server contract: a callable app(environ, start_response). ASGI is the asynchronous successor: an async callable that handles HTTP, WebSockets, and lifespan over a connection scope.