Python Glossary: 100+ Terms Explained
1 · The lesson
readA reference dictionary of Python terms — from "argument" to "yield". Bookmark this page. Each definition is one paragraph or shorter. Where there's a deeper lesson, the term links to it.
Jump: A · B · C · D · E · F · G · H · I · J · K · L · M · N · O · P · Q · R · S · T · U · V · W · Y
A
ABC (Abstract Base Class) — A class that cannot be instantiated directly and defines an interface subclasses must implement. Defined via the abc module with @abstractmethod. Useful for enforcing a contract across a family of classes. See OOP.
__all__ — A module-level list of names that defines what from module import * exports. Also signals the public API of a module to readers and linters. See Modules.
Annotation — A piece of metadata attached to a variable, parameter, or return value, written after a colon: x: int = 5. Annotations are stored in __annotations__ and used by type checkers like mypy; Python itself ignores them at runtime. See Type hints.
Argument — A value passed to a function when it is called. print("hi") calls print with the argument "hi". Contrast with parameter (the name in the function's def line). See Functions.
Async / asynchronous — Code that pauses at await points so other tasks can run on the same thread. Python's asyncio module provides the event loop that schedules coroutines. See Async / Await.
Attribute — A value attached to an object, accessed with dot notation: obj.x. Methods are simply callable attributes. Attributes can live on the instance, the class, or be looked up via descriptors. See OOP.
B
Backreference (regex) — A reference to a previously matched group inside the same pattern, written as \1, \2, etc. (\w+) \1 matches a repeated word. See Regex.
BaseException — The root of Python's exception hierarchy. Most user exceptions inherit from Exception, not BaseException, because SystemExit and KeyboardInterrupt also derive from BaseException and should rarely be caught. See Exceptions.
bool() — The built-in that converts any value to True or False using truthiness rules. Empty containers, 0, None, and "" are falsy; everything else is truthy.
Boolean — The type with exactly two values: True and False. A subclass of int, so True + 1 == 2 and sum([True, True, False]) == 2.
Built-in — A name available without any import, such as len, print, range, or Exception. Defined in the builtins module, which is implicitly imported into every scope.
Bytecode — The compact, platform-independent instructions Python compiles your source to before the interpreter runs it. Cached on disk as .pyc files in __pycache__/.
Bytes — An immutable sequence of integers in 0..255, written b"hello". Used for binary data and network I/O. Contrast with str, which is a sequence of Unicode code points; encode with .encode("utf-8") to convert between them.
C
Cache (functools) — A way to memoise expensive function results using @functools.cache or @functools.lru_cache(maxsize=N). The decorated function stores results keyed by its arguments. See Decorators.
Callable — Any object that can be invoked with (). Functions, classes, methods, and instances with a __call__ method are all callable. Check with callable(obj).
ChainMap — A collections class that groups multiple dicts into a single view, searching them in order. Handy for layered configuration (defaults, user, environment). See Collections.
Class — A blueprint for creating objects, defined with class Name:. Instances share the methods and class attributes defined inside. See OOP.
Class attribute — A name bound at class level rather than on an instance. Shared across all instances unless shadowed by an instance attribute of the same name. Mutable class attributes (lists, dicts) are a common bug source. See OOP.
Classmethod — A method that receives the class itself as its first argument instead of an instance. Declared with @classmethod; commonly used for alternative constructors like dict.fromkeys. See OOP.
Closure — A function that remembers variables from the enclosing scope where it was defined, even after that scope has returned. The foundation for decorators and many functional patterns. See Decorators.
Comprehension — A concise expression that builds a list, set, dict, or generator by iterating in a single line: [x*x for x in nums if x > 0]. See Comprehensions.
Conditional — A construct that runs code only when a test is true: if, elif, else. Also covers the conditional expression a if cond else b. See Conditionals.
Context manager — An object that defines __enter__ and __exit__ so it can be used with with. Guarantees cleanup (closing files, releasing locks) even on exceptions. See Context managers.
Coroutine — A function defined with async def. Calling it returns a coroutine object; you must await it (or schedule it with the event loop) to actually run. See Async / Await.
Counter — A collections dict subclass that counts hashable items: Counter("mississippi") gives {'i': 4, 's': 4, ...}. Has most_common(n) and supports arithmetic. See Collections.
Cython — A separate language and compiler that translates Python-like code into C extensions for speed. Not part of standard Python, but a common option when pure Python is too slow.
D
Dataclass — A class decorated with @dataclass that auto-generates __init__, __repr__, and __eq__ from class-level annotations. Removes the boilerplate of plain data containers. See Dataclasses.
datetime — The standard module for working with dates, times, and durations. Key types: date, time, datetime, timedelta. See Datetime.
Decorator — A callable that wraps another callable to add behaviour, applied with @decorator syntax above a def. Common uses: caching, logging, registration, access control. See Decorators.
deepcopy — copy.deepcopy(obj) recursively copies an object and every object it references. Use it when shallow copies share mutable internals you want to isolate.
Default argument — A parameter with a fallback value used when the caller omits it: def f(x=10). Never use a mutable default like [] — it is created once and reused across calls. See Functions.
defaultdict — A collections dict that creates a default value for missing keys via a factory function. defaultdict(list) returns [] for any new key. See Collections.
Deque — collections.deque, a double-ended queue with O(1) appends and pops from either end. Use it instead of a list when you need a FIFO queue. See Collections.
Descriptor — An object that customises attribute access by defining __get__, __set__, or __delete__. Properties, methods, and classmethods are all built on descriptors. See Descriptors.
Dict — Built-in mapping from hashable keys to arbitrary values: {"a": 1, "b": 2}. Preserves insertion order since Python 3.7. See Dictionaries.
Docstring — A string literal placed as the first statement inside a module, class, or function. Accessible via obj.__doc__ and shown by help(). Use triple quotes.
Duck typing — "If it walks like a duck and quacks like a duck, it's a duck." Python cares about whether an object supports the operations you need, not what class it belongs to.
Dunder method — A method whose name begins and ends with double underscores, like __init__, __len__, __iter__. Hook into language syntax (operators, with, iteration). See OOP.
Dynamic typing — Variables are bound to objects, not to types; the same name can hold an int then a str later. Type checking happens at runtime when an operation is attempted.
E
EAFP — "Easier to Ask Forgiveness than Permission." A Pythonic style that tries an operation and catches the exception if it fails, instead of pre-checking. Contrast with LBYL. See Exceptions.
Encoding — A mapping between text characters and bytes. UTF-8 is the default and the right answer in almost every case; legacy systems may use latin-1, cp1252, or others.
Enum — A class from the enum module whose members are named constants. class Colour(Enum): RED = 1; BLUE = 2. Members are singletons and comparable by identity.
Environment variable — A key-value pair set in the OS environment, read in Python with os.environ["NAME"] or os.getenv("NAME", default). Standard place for secrets and per-environment config. See Env config.
eval — Built-in that executes a string as a Python expression. Dangerous on untrusted input; use ast.literal_eval for safe parsing of literals.
ExceptionGroup — A container for multiple exceptions raised together, introduced in Python 3.11. Caught with except* syntax. Used by asyncio.TaskGroup.
except — The clause that catches an exception raised inside a try block. Can be qualified by type and bound to a name: except ValueError as e:. See Exceptions.
Exception — An object representing an error or unusual condition, raised with raise and caught with try/except. The base class for normal user exceptions. See Exceptions basics.
ExitStack — A contextlib helper that combines multiple context managers dynamically. Useful when the number of resources is not known at write time. See Context managers.
Expression — Any piece of code that evaluates to a value: 2 + 2, f(x), [a for a in xs]. Contrast with a statement, which performs an action.
extend (list method) — list.extend(iterable) appends every item from the iterable to the list in place. Differs from append, which adds the iterable itself as one element.
F
f-string — A formatted string literal prefixed with f, where {expr} is replaced by the value of expr: f"x = {x:.2f}". The fastest and clearest formatting tool in modern Python. See f-strings.
Filter — The built-in filter(pred, iterable) keeps items for which pred(item) is true. A comprehension [x for x in xs if pred(x)] is usually clearer.
Finally — A try clause that always runs, exception or not. Used for cleanup that must happen even on failure. Largely superseded by context managers. See Exceptions.
First-class function — In Python, functions are objects you can pass as arguments, return from other functions, store in lists, and bind to names. This enables decorators, callbacks, and functional patterns.
Float — A 64-bit IEEE 754 floating-point number. Subject to rounding; 0.1 + 0.2 != 0.3. Use decimal.Decimal for money and exact fractions.
for-loop — A statement that iterates over any iterable: for item in iterable: .... Python's for is foreach; there is no C-style three-part form. See Loops.
Frozenset — An immutable, hashable version of set. Useful as a dict key or set member. See Sets.
Function — A reusable block of code defined with def name(params): ... that may return a value. Calling without return yields None. See Functions.
functools — Standard library module of higher-order tools: cache, lru_cache, partial, reduce, wraps, singledispatch. See Decorators.
Future (concurrent) — An object representing the eventual result of an asynchronous operation, returned by executors in concurrent.futures and awaitable in asyncio.
G
Generator — A function that uses yield to produce a sequence of values lazily. Each call to next() resumes execution until the next yield. Saves memory for large or infinite sequences. See Generators.
Generator expression — A lazy comprehension written with parentheses: (x*x for x in xs). Builds no list; yields values one at a time. See Generators.
Generic — A type parameterised by other types, like list[int] or dict[str, User]. Defined with Generic[T] or, in modern syntax, class Stack[T]:. See Type hints.
GIL (Global Interpreter Lock) — A mutex in CPython that allows only one thread to execute Python bytecode at a time. Threads still help with I/O-bound work; for CPU-bound parallelism, use processes or release the GIL in C extensions. See Multiprocessing.
global — A statement that binds a name in the module-level scope from inside a function. Required only when you need to assign to a global, not to read one. See Functions.
groupby — itertools.groupby(iterable, key) yields runs of consecutive items sharing a key. Sort first if you want global grouping. See itertools.
H
Hash — An integer derived from an object via hash(obj). Used by dicts and sets to locate entries. Two equal objects must have equal hashes.
Hashable — An object is hashable if it has a stable __hash__ and supports ==. All immutable built-ins (int, str, tuple of hashables, frozenset) are hashable; lists and dicts are not.
Heap (heapq) — A binary heap implemented on top of a list, exposed by the heapq module. heappush and heappop are O(log n) and always return the smallest item. The basis for priority queues.
I
Identity (is) — a is b is true when a and b are the same object in memory, not merely equal. Use is for None, True, False; use == for value comparison.
Immutable — An object whose value cannot change after creation: int, float, str, tuple, frozenset, bytes. "Modifying" them actually produces new objects.
Import — A statement that loads another module and binds names from it. import x, from x import y, from x import y as z. See Modules.
Indentation — Leading whitespace that defines block structure in Python. Four spaces per level is the standard; mixing tabs and spaces is a syntax error.
Index — The integer position of an item in a sequence, starting at 0. Negative indices count from the end: s[-1] is the last item.
IndexError — Raised when a sequence index is out of range, e.g. [1, 2][5]. See the IndexError reference.
Inheritance — Defining a class that reuses and extends another via class Child(Parent):. The child receives the parent's attributes and methods. See Inheritance.
__init__ — The initialiser method called right after a new instance is created. Sets up instance attributes; does not return a value. See OOP.
__init_subclass__ — A class method on a parent that runs each time a subclass is defined. Lets a base class customise or validate its descendants without a metaclass.
Instance — A specific object produced by calling a class: c = Car() creates an instance of Car. See OOP.
int — Built-in arbitrary-precision integer type. No overflow; 2**1000 is just an int. Booleans are a subclass.
Interpreter — The program that reads your Python source, compiles it to bytecode, and executes it. The reference implementation is CPython; alternatives include PyPy and GraalPy.
Iterable — Any object you can loop over with for. Internally, iter(obj) returns an iterator. Lists, tuples, dicts, sets, strings, files, and generators are all iterables.
Iterator — An object with a __next__ method that yields the next item or raises StopIteration. Every iterator is also iterable (its __iter__ returns itself).
itertools — Standard library module of lazy iterator-building blocks: chain, cycle, repeat, count, groupby, product, permutations, combinations. See itertools.
J
JSON — JavaScript Object Notation, a text format for exchanging structured data. Maps cleanly to Python dicts, lists, strings, numbers, booleans, and None. See CSV / JSON.
json.dumps / json.loads — dumps serialises a Python object to a JSON string; loads parses a JSON string back. dump / load work with file objects. See CSV / JSON.
K
KeyError — Raised when a dict lookup fails: {}["missing"]. See the KeyError reference.
Keyword (reserved word) — A name reserved by the language grammar and unusable as an identifier: if, else, for, def, class, lambda, import, and so on. Listed in keyword.kwlist.
Keyword argument — An argument passed by name: f(x=1, y=2). Order is independent of the function signature; readability improves at call sites. See Functions.
L
Lambda — An anonymous, single-expression function: lambda x: x + 1. Useful for short callbacks; prefer def when the logic grows. See Lambda.
LEGB rule — Python's name lookup order: Local, Enclosing, Global, Built-in. Each unqualified name is searched in that order, and the first match wins.
List — A mutable, ordered sequence: [1, 2, 3]. Supports indexing, slicing, append, and arbitrary item types. See Lists.
List comprehension — A comprehension that produces a list: [x*2 for x in xs]. See Comprehensions.
Literal — A value written directly in source: 42, "hi", [1, 2], None. The compiler emits the value without any function call.
Logging — Producing structured records of program events via the logging module. Preferred over print for any code beyond a script. See Logging.
lru_cache — @functools.lru_cache(maxsize=N) decorator that caches function results with a least-recently-used eviction policy. Use @cache for unbounded caching. See Decorators.
M
Map — The built-in map(func, iterable) lazily applies func to each item. A comprehension [func(x) for x in xs] is usually clearer.
Memoization — Caching a function's results keyed by its arguments so repeated calls are O(1). Implemented in Python with @functools.cache or @lru_cache.
Metaclass — The class of a class. Controls how classes themselves are created. type is the default metaclass. Rarely needed; use decorators or __init_subclass__ first. See Metaclasses.
Method — A function defined inside a class. When accessed on an instance, the instance is automatically bound as the first argument (self). See OOP.
Method resolution order (MRO) — The linear order Python searches base classes during attribute lookup, computed by the C3 algorithm. Inspect with Cls.__mro__. See Inheritance.
Mixin — A class designed to be combined with others via multiple inheritance to add a focused capability (e.g. SerialisableMixin). Never instantiated alone. See Inheritance.
Module — A single .py file that can be imported. Its top-level names form its public surface. See Modules.
Mutable — An object whose state can change in place: list, dict, set, most user classes. Mutability has implications for default arguments, hashing, and aliasing.
N
Name — An identifier bound to an object via assignment, def, class, or import. Python names are references, not boxes that hold values.
NameError — Raised when a name is used before being defined in any reachable scope. See the NameError reference.
namedtuple — collections.namedtuple("Point", ["x", "y"]) creates a tuple subclass with named fields. Modern alternative: @dataclass(frozen=True) or typing.NamedTuple. See Collections.
None — The singleton sentinel returned by functions that have no other value to return, and the canonical "missing" marker. Compare with is None.
NoneType — The type of None. type(None) is NoneType. There is exactly one instance.
nonlocal — A statement that binds a name in the nearest enclosing function scope (but not module scope) from inside a nested function. Required to assign to such a name. See Functions.
numpy — Third-party library for fast numerical arrays and linear algebra. Foundation of the scientific Python stack; install with pip install numpy.
O
Object — The base class of every class in Python. Every value, including functions and classes, is an object with attributes and a type.
OOP (Object-Oriented Programming) — A style that bundles state and behaviour into classes and instances, using inheritance, encapsulation, and polymorphism. See OOP.
Optional — Optional[T] is shorthand for T | None, signalling that a value may be missing. Modern syntax prefers T | None. See Type hints.
OrderedDict — A collections dict subclass that historically preserved insertion order; now mostly redundant since plain dict does the same in 3.7+. Still useful for move_to_end and order-sensitive equality.
Override — Defining a method in a subclass with the same name as one in a parent, replacing the parent's behaviour. Use super().method() to delegate. See Inheritance.
P
Package — A directory of modules with an __init__.py (or a namespace package without one). Imported as a dotted path: package.subpackage.module. See Packaging.
Parameter — A name listed in a function's def line that receives an argument when the function is called. See Functions.
pathlib — Standard library module providing the Path class for filesystem paths as objects with methods like .read_text(), .exists(), and .glob(). Preferred over raw os.path strings. See File I/O.
PEP — Python Enhancement Proposal, a numbered document describing a language change or convention. PEP 8 is the style guide; PEP 20 is the Zen of Python.
pickle — Standard module that serialises Python objects to bytes for storage or transport. Never unpickle untrusted data — it can execute arbitrary code.
pip — Python's package installer, used to fetch third-party libraries from PyPI: pip install requests. See pip and stdlib.
Polymorphism — The ability for different types to be used through a shared interface. In Python this is usually duck typing: any object with the right methods works. See OOP.
Property — A class attribute defined with @property that runs a method on access, letting computed values look like plain attributes. Pair with @x.setter to allow assignment. See OOP.
Pure function — A function whose output depends only on its inputs and that produces no side effects. Easier to test, reason about, and cache.
Pyenv — A third-party tool for installing and switching between multiple Python versions per shell or project. Not the same as venv.
pytest — The de facto third-party testing framework. Tests are plain functions whose names start with test_; assert is enough — no special API needed. See Testing.
Q
Queue (queue module) — Thread-safe FIFO, LIFO, and priority queues for producer-consumer patterns. Distinct from collections.deque, which is not thread-safe but faster.
R
Raise — The statement that throws an exception: raise ValueError("bad"). Use raise ... from e to chain causes. See Exceptions.
range — Built-in that lazily produces a sequence of integers: range(stop), range(start, stop), range(start, stop, step). Memory-efficient — values are computed on demand.
Recursion — A function that calls itself, usually with a smaller input, until it hits a base case. CPython's default recursion limit is around 1000; raise with sys.setrecursionlimit if you must.
Regular expression (regex) — A pattern language for matching and extracting text, accessed in Python via the re module. See Regex.
REPL — Read-Eval-Print Loop, the interactive Python shell you get by running python with no arguments. Great for exploration; try python -i script.py to drop in after running a file.
Repr (__repr__) — A dunder method returning an unambiguous, developer-facing string for an object. Ideally a valid expression that recreates it. Falls back from str() when __str__ is undefined.
Return — The statement that exits a function and supplies a value. A function with no return (or a bare return) yields None. See Functions.
S
Scope — The region of code where a name is visible. Python has four (LEGB): local, enclosing, global, built-in.
Self — The conventional name for the first parameter of an instance method, bound to the instance the method was called on. Not a keyword — any name works, but use self. See OOP.
Sequence — An ordered, indexable collection: list, tuple, str, bytes, range. Supports len, indexing, slicing, and iteration.
Set — A mutable, unordered collection of unique hashable items: {1, 2, 3}. Fast membership tests and set algebra (|, &, -, ^). See Sets.
Set comprehension — A comprehension that builds a set: {x % 7 for x in xs}. See Comprehensions.
Setter — A method paired with a property that runs on assignment: @x.setter. Lets you validate or compute on write. See OOP.
Side effect — Any change a function makes beyond returning a value: mutating an argument, writing to a file, printing. Pure functions have none.
Singleton — A class with exactly one instance. None, True, False, and Ellipsis are language-level singletons. User singletons are usually a sign you want a module instead.
Slice — A way to extract or assign a sub-range of a sequence: s[start:stop:step]. Negative indices and omitted bounds are allowed. See Slicing cheat sheet.
Slot (__slots__) — A class attribute listing the only instance attributes allowed. Replaces the per-instance __dict__ with a fixed array, saving memory and forbidding ad-hoc attributes.
Sorted vs sort — sorted(iterable) returns a new sorted list and works on any iterable. list.sort() sorts in place and returns None. Both accept key and reverse.
Standard library — The set of modules that ship with Python: os, sys, re, json, datetime, collections, itertools, and many more. No pip install needed. See pip and stdlib.
Statement — A unit of execution that performs an action: assignment, if, for, def, return, import. Contrast with expression.
staticmethod — A method declared with @staticmethod that receives neither self nor cls. Just a function namespaced inside a class. See OOP.
String — An immutable sequence of Unicode characters, written "text" or 'text'. Supports slicing, formatting, and a rich method API. See Strings.
Stub — A .pyi file containing type hints for code (often third-party or C) that has none inline. Loaded by type checkers, ignored at runtime.
super — A built-in that returns a proxy delegating attribute lookups to the parent classes per the MRO. Use super().__init__(...) to call a parent's initialiser. See Inheritance.
T
Ternary — Python's conditional expression: value_if_true if condition else value_if_false. One line, returns a value. Do not nest deeply.
Truthy / Falsy — How any value behaves in a boolean context. Falsy: False, None, 0, 0.0, "", [], {}, (), set(). Everything else is truthy. Avoid len(x) > 0 when if x: will do.
try / except — The statement that runs guarded code in a try block and handles raised exceptions in matching except clauses. Optional else runs on success; finally always runs. See Exceptions basics.
Tuple — An immutable, ordered sequence: (1, 2, 3). Often used for fixed-size records and as dict keys. The comma makes the tuple — (x) is just x, but (x,) is a one-tuple. See Tuples.
type — Built-in that returns an object's class: type(3) is int. Also the default metaclass: type(name, bases, dict) creates a new class dynamically.
Type hint — An annotation declaring the expected type of a variable, parameter, or return value. Checked by tools like mypy or pyright; ignored at runtime. See Type hints.
TypeError — Raised when an operation gets an argument of the wrong type, like "5" + 5 or len(42). See the TypeError concat reference.
TypedDict — A typing construct describing dicts with a fixed set of string keys and per-key value types. Useful for JSON-shaped data. See Type hints.
TypeVar — A placeholder used in generic type hints: T = TypeVar("T") then def first(xs: list[T]) -> T. Modern syntax: def first[T](xs: list[T]) -> T. See Type hints.
U
Unbound — A name with no value in the current scope. Reading it raises NameError; assigning to a local name before it is defined raises UnboundLocalError. See the UnboundLocalError reference.
Unicode — The character set Python str uses internally. Each character has a code point; chr and ord convert between characters and integers.
Union (type) — A type hint meaning "one of these types": int | str (or Union[int, str] in older code). See Type hints.
unittest — The standard library's xUnit-style test framework. Works, but most new projects prefer pytest for its lighter syntax. See Testing.
UTF-8 — The dominant encoding for Unicode text. ASCII-compatible, variable-width, the default for Python source files and most modern I/O. Always pass encoding="utf-8" when opening text files.
V
ValueError — Raised when an operation receives the right type but an unacceptable value, like int("abc"). See the ValueError reference.
Variable — A name bound to an object. Python variables are references; assignment never copies. See Variables.
Virtual environment (venv) — An isolated Python install with its own site-packages, created by python -m venv .venv. Keeps project dependencies independent. See Virtual environments.
W
Walrus operator — Assignment expression := that binds and returns a value inline: if (n := len(data)) > 10: .... Useful in comprehensions and while conditions; avoid when a plain assignment is clearer.
while loop — A statement that repeats a block as long as its condition is true. Best for unknown iteration counts; prefer for over range for counted loops. See Loops.
with statement — The syntax for using a context manager: with open(p) as f: .... Guarantees cleanup. See Context managers.
wraps (functools) — @functools.wraps(func) inside a decorator copies the wrapped function's name, docstring, and metadata onto the wrapper. Always use it when writing decorators. See Decorators.
Y
yield — A statement inside a function that turns it into a generator. Each yield suspends the function, returning a value; the next next() resumes after it. See Generators.
yield from — Delegates iteration to another iterable from inside a generator: yield from sub_gen(). Forwards values, sent inputs, and return values transparently.
Spot a missing term or unclear definition? This page is part of the Reference path — pair it with the cheat sheets and error references for a complete lookup library.