- __call__ advanced
The special method that lets an object be called like a function using parentheses. It is useful for objects that carry state between calls, such as configured models or decorators implemented as classes.
Example. class Scale: def __call__(self, x): return x * self.k; double = Scale(2); double(5) returns 10.
Related: Dunder method, Callable, Decorator, Closure
- __enter__ and __exit__ advanced
The pair of special methods that make a class usable as a context manager. __enter__ runs as the block starts and returns the value bound after 'as'; __exit__ runs at the end and receives any exception raised.
Example. class Timer: __enter__ records the start time and __exit__ prints elapsed seconds after the with block ends.
Related: Context manager, with statement, Dunder method, contextlib
- __eq__ intermediate
The special method defining what == means for objects of a class. Without it, two objects are equal only if they are the very same object. Defining it usually calls for defining __hash__ too.
Example. def __eq__(self, o): return self.id == o.id treats two Customer objects with the same id as equal.
Related: __hash__, Dunder method, Operator overloading, Dataclass
- __getitem__ intermediate
The special method that lets an object be indexed or sliced with square brackets. Defining it also makes the object iterable by position, which is how datasets in ML frameworks often expose their samples.
Example. def __getitem__(self, i): return self.data[i] lets you write ds[5] to fetch the sixth sample.
Related: __len__, Dunder method, Iterator, Sequence
- __hash__ advanced
The special method returning an integer used to place an object in sets and as a dictionary key. Objects that compare equal must have equal hashes, and mutable objects are usually left unhashable.
Example. def __hash__(self): return hash(self.id) lets Customer objects be stored in a set by their id.
Related: __eq__, Dunder method, Hashable, Dataclass
- __init__ beginner
The special method Python calls right after a new object is created, used to set its starting attributes. It receives the new object plus any arguments passed when calling the class, and it must not return a value other than None.
Example. def __init__(self, name, age): self.name = name; self.age = age runs when you write Person('Meera', 29).
Related: Constructor, Dunder method, self, Instance attribute
- __init__.py intermediate
A file that marks a directory as a regular Python package and runs when the package is imported. It can be empty or expose selected names so users import them from the package directly.
Example. Adding from .cleaning import clean_text to mypkg/__init__.py lets users write from mypkg import clean_text.
Related: Package, Module, Import, Namespace package
- __len__ intermediate
The special method that returns how many items an object holds, called by the built-in len(). Defining it also makes an object usable in truth tests, where zero length counts as false.
Example. class Batch: def __len__(self): return len(self.rows) makes len(batch) return the number of rows.
Related: Dunder method, __getitem__, Protocol, Container
- __main__ guard intermediate
The idiom if __name__ == '__main__': that runs code only when a file is executed directly and not when it is imported. It lets a file act as both a reusable module and a script.
Example. Putting main() under the guard lets tests import functions from the file without launching the whole program.
Related: Module, Script, Import, Package
- __new__ advanced
The special method that actually creates and returns a new object before __init__ initialises it. It is rarely overridden, mainly for immutable types or controlling instance creation, as in singletons.
Example. def __new__(cls): if not cls._inst: cls._inst = super().__new__(cls); return cls._inst reuses one instance.
Related: __init__, Constructor, Singleton, Metaclass
- __repr__ intermediate
The special method returning an unambiguous text form of an object, intended for developers and debugging. It is used by the interactive prompt and by print for containers. Ideally it looks like code that could recreate the object.
Example. def __repr__(self): return f'Point({self.x}, {self.y})' makes a point display as Point(3, 4) in a list.
Related: __str__, Dunder method, f-string, Debugging
- __str__ intermediate
The special method returning a readable text form of an object for end users. It is used by print() and str(). If it is missing, Python falls back to __repr__.
Example. def __str__(self): return f'{self.name} (Rs {self.price})' prints a product as 'Pen (Rs 10)'.
Related: __repr__, Dunder method, f-string, Class
- abc module advanced
A standard library module that supplies the tools for defining abstract base classes, including the ABC helper class and the @abstractmethod decorator. Instantiating a class with unimplemented abstract methods raises TypeError.
Example. from abc import ABC, abstractmethod; then mark predict with @abstractmethod so subclasses must define it.
Related: Abstract base class, Decorator, Interface, Inheritance
- Abstract base class advanced
A class that cannot be instantiated directly and defines methods subclasses must implement. Python's abc module supports it. It enforces a contract so every subclass offers a required interface. It is a way to guarantee that every concrete class provides certain methods.
Example. class Model(ABC) with @abstractmethod predict() forces every subclass, like LinearModel, to implement predict().
Related: abc module, Interface, Inheritance, Polymorphism
- Assertion beginner
A statement that checks a condition is true and raises an AssertionError if not. In tests it verifies expected results; in code it documents assumptions during development. Assertions can be switched off with the -O flag, so they should not validate user input.
Example. assert len(rows) > 0, 'no data loaded' stops with the message if rows is empty.
Related: pytest, Unit test, Exception, Test case
- async and await intermediate
Keywords for asynchronous code. async def defines a coroutine function; await pauses it until another awaitable finishes, letting the event loop run other tasks meanwhile. Both keywords work only inside async def functions, apart from special cases.
Example. async def get(): r = await client.get(url) pauses at the request while other coroutines proceed.
Related: Coroutine, asyncio, Event loop, Awaitable
- asyncio intermediate
Python's standard library for writing single-threaded concurrent code with async and await, driven by an event loop. It suits programs that spend most of their time waiting on networks, such as calling many APIs.
Example. asyncio.gather(fetch(a), fetch(b)) waits on two web requests at once within one thread.
Related: Event loop, async and await, Coroutine, Concurrency
- Attribute beginner
A named piece of data or behaviour attached to an object, reached with dot notation. It may hold a plain value or a method. Python looks it up on the object first, then on its class and parent classes.
Example. student.name reads the name attribute; student.grade = 'A' creates or updates the grade attribute.
Related: Instance attribute, Class attribute, Method, Object
- Circular import advanced
A situation where two modules import each other, directly or through a chain, so one is used before it has finished loading. It usually raises an ImportError and is fixed by restructuring or delayed imports.
Example. a.py imports b.py, which imports a.py again, and accessing a name from a partly loaded module fails.
Related: Import, Module, Package, ImportError
- Class beginner
A blueprint that bundles data (attributes) and behaviour (methods) into a new kind of object. Code builds individual objects from it. It lets you model real things, such as a customer or a model wrapper, in one reusable, named unit.
Example. class Loan: def __init__(self, amount): self.amount = amount loan = Loan(50000) creates a Loan object holding 50000 rupees.
Related: Object, Instance, Method, Attribute
- Class attribute intermediate
A variable defined in the body of a class rather than on an individual object, so all objects of the class share one value. Reading it through an object works, but assigning through an object creates a separate instance attribute instead.
Example. class Tax: rate = 0.18 Tax.rate is 0.18 for every Tax object, like a shared GST rate.
Related: Instance attribute, Class, Attribute, Static method
- Class method intermediate
A method bound to the class instead of an object, marked with @classmethod and receiving the class as its first argument (usually cls). It is often used as an alternative constructor.
Example. @classmethod def from_csv(cls, path): return cls(read(path)) builds an object from a file, e.g. Dataset.from_csv('sales.csv').
Related: Static method, Decorator, Instance method, Constructor
- Closure intermediate
A function that remembers variables from the enclosing scope in which it was defined, even after that outer function has finished. It carries private state without needing a class. This is how decorators and factories keep configuration between calls.
Example. def make_counter(): n = 0; def inc(): nonlocal n; n += 1; return n; return inc gives a counter that remembers n between calls.
Related: Nonlocal, Decorator, Scope, Higher-order function
- collections module intermediate
A standard library module offering specialised containers, including Counter, defaultdict, deque, namedtuple and OrderedDict. They cover common needs, like counting items or fast queue operations, better than general lists and dictionaries.
Example. Counter('banana') returns counts a:3, n:2, b:1 in one call.
Related: defaultdict, Counter, deque, namedtuple
- Composition intermediate
A design approach where an object holds other objects as attributes and delegates work to them, instead of inheriting from them. It expresses a 'has-a' relationship and is often more flexible than deep class hierarchies.
Example. A Pipeline object stores a Tokenizer and a Model as attributes and calls them in order, rather than inheriting from either.
Related: Inheritance, Class, Polymorphism, Encapsulation
- conftest.py advanced
A special pytest file whose fixtures and hooks are automatically available to all tests in its directory and below, without importing. It is used to share common setup across test files.
Example. Placing a database fixture in tests/conftest.py makes it usable in every test module under tests.
Related: Fixture, pytest, Unit test, Test suite
- Constructor beginner
The code path that builds and prepares a new object when you call a class. In Python this is the class call itself, which runs __new__ to allocate the object and then __init__ to fill in its initial state.
Example. Calling Model('resnet', layers=50) constructs a Model object whose __init__ stores the name and layer count.
Related: __init__, __new__, Class, Instance
- Context manager intermediate
An object that sets something up before a block of code and reliably cleans up afterwards, used with the with statement. It guarantees that resources such as files and locks are released even if an error occurs.
Example. with open('data.csv') as f: reads the file and closes it automatically at the end of the block.
Related: with statement, __enter__ and __exit__, contextlib, Resource management
- contextlib advanced
A standard library module offering helpers for context managers, such as the @contextmanager decorator that turns a generator function into one, plus suppress and closing. It removes the need to write a full class for simple cases.
Example. @contextmanager def timer(): start = time.time(); yield; print(time.time() - start) is then used as with timer():.
Related: Context manager, Generator, Decorator, with statement
- Coroutine advanced
A function defined with async def whose execution can be paused and resumed. Calling it returns a coroutine object that does nothing until awaited or scheduled on an event loop.
Example. c = fetch(url) only creates a coroutine object; await c or asyncio.run(c) actually runs it.
Related: async and await, asyncio, Event loop, Generator
- Counter intermediate
A dictionary subclass in the collections module that counts how many times each item appears in an iterable. It offers helpers such as most_common() for ranking frequent items. It works like a tally sheet keyed by item, ideal for word frequencies.
Example. Counter(words).most_common(3) returns the three most frequent words in a list of tokens.
Related: collections module, defaultdict, Dictionary, Word frequency
- Dataclass intermediate
A class decorated with @dataclass that automatically generates __init__, __repr__ and __eq__ from annotated fields. It removes boilerplate for classes that mainly hold data, such as configuration records. It is part of the standard library from Python 3.7 onward.
Example. @dataclass class Config: lr: float = 0.001; epochs: int = 10 then Config(epochs=5) works with no hand-written __init__.
Related: namedtuple, Type hint, __repr__, Pydantic
- Decorator intermediate
A function that takes another function (or class) and returns a modified version, applied with @name above the definition. Decorators add behaviour such as logging, caching or access checks without editing the original code.
Example. @timed above def train(): wraps train so every call also reports how many seconds it took.
Related: Closure, Higher-order function, functools.wraps, Function
- Decorator with arguments advanced
A decorator factory: a function that takes settings and returns the actual decorator. It needs three nested layers, the factory, the decorator and the wrapper, and is written as @name(args).
Example. @retry(times=3) uses a factory retry that builds a decorator making a flaky API call retry up to three times.
Related: Decorator, Closure, Higher-order function, functools.wraps
- defaultdict intermediate
A dictionary from the collections module that automatically creates a default value for a missing key using a factory function you supply. It removes the need for checks before appending or counting.
Example. d = defaultdict(list); d['Delhi'].append('Rohan') works even though 'Delhi' was never added.
Related: collections module, Counter, Dictionary, namedtuple
- Descriptor advanced
An object defining __get__, __set__ or __delete__ that controls how an attribute is read or written when it sits in a class. Properties, methods and many ORM fields are built on this protocol.
Example. A Positive descriptor whose __set__ raises ValueError for negative numbers can guard several attributes across classes.
Related: Property, Attribute, Dunder method, Metaclass
- Duck typing intermediate
A style where an object's suitability is decided by whether it has the needed methods and attributes, not by its declared class. The saying is: if it walks and quacks like a duck, treat it as a duck.
Example. len(x) works on a list, string or any object defining __len__, with no shared parent class required.
Related: Polymorphism, Protocol, Dunder method, Type hint
- Dunder method intermediate
A special method whose name starts and ends with double underscores, such as __len__ or __add__. Python calls these automatically to support built-in syntax and functions on your own classes. Also called a magic or special method.
Example. Defining __len__ in your class lets len(obj) work; defining __add__ lets you write obj1 + obj2.
Related: __repr__, __init__, Operator overloading, Protocol
- Encapsulation intermediate
Bundling data with the methods that use it and limiting direct outside access to the internals. It protects an object's state from accidental misuse and lets the internal design change without breaking users of the class.
Example. A BankAccount keeps _balance internal and exposes deposit() and withdraw(), which check that the amount is valid.
Related: Property, Name mangling, Class, Abstraction
- Fixture intermediate
A reusable piece of setup, and optional teardown, that pytest supplies to tests by name through function arguments. It provides things such as sample data, database connections or temporary files.
Example. @pytest.fixture def sample_df(): return pd.DataFrame(...) then def test_x(sample_df): receives that data.
Related: pytest, Parametrized test, conftest.py, Unit test
- functools intermediate
A standard library module of tools for working with functions, including partial, lru_cache, reduce, wraps and singledispatch. It supports functional style and performance helpers without extra dependencies. It ships with Python, so no installation is needed.
Example. functools.partial(pow, exp=2) creates a new function that always squares its input.
Related: functools.lru_cache, functools.partial, Higher-order function, Decorator
- functools.lru_cache intermediate
A decorator that remembers the results of a function for previously seen arguments, evicting the least recently used ones when full. It speeds up pure functions with repeated inputs, such as recursive calculations.
Example. @lru_cache(maxsize=None) on a recursive fib(n) makes fib(50) fast because each value is computed once.
Related: Memoization, Decorator, functools, Dynamic programming
- functools.partial intermediate
A tool that fixes some arguments of an existing function to create a new function with fewer parameters. It helps adapt functions to interfaces that call them with fewer inputs.
Example. double = partial(multiply, 2) then double(7) returns 14.
Related: functools, Higher-order function, Lambda, Closure
- functools.wraps advanced
A decorator from the functools module used inside your own decorators to copy the original function's name, docstring and other metadata onto the wrapper. Without it, the decorated function appears to have the wrapper's identity.
Example. Adding @wraps(func) above the wrapper keeps train.__name__ equal to 'train' instead of 'wrapper'.
Related: Decorator, Closure, functools, Docstring
- Future advanced
An object representing a result that will be available later, either from an executor or the event loop. You can check whether it is done, wait for it or retrieve its result or exception.
Example. future = executor.submit(train_model) returns immediately; future.result() waits and returns the outcome.
Related: concurrent.futures, Task, Coroutine, asyncio
- Generator intermediate
A special iterator built by a function that uses yield. It pauses at each yield, remembers its local state, and continues from there on the next request. It produces values lazily, one at a time, saving memory.
Example. def evens(n): for i in range(0, n, 2): yield i produces even numbers on demand without building a list.
Related: yield, Generator expression, Lazy evaluation, Iterator
- Generator expression intermediate
A compact way to build a generator using comprehension-like syntax in parentheses. It computes items lazily instead of creating a full list in memory, which suits large data pipelines. It is the lazy counterpart of a list comprehension.
Example. sum(x * x for x in range(1_000_000)) adds the squares without storing a million numbers.
Related: Generator, List comprehension, Lazy evaluation, Iterator
- Generic advanced
A class or function written to work with many types while keeping type information, using type variables. It lets checkers know that a container of integers returns integers, not just any object.
Example. list[int] is a generic list holding integers; a checker knows that lst[0] is an int.
Related: TypeVar, Type hint, Protocol, mypy
- Inheritance beginner
A mechanism where a new class takes on the attributes and methods of an existing class and may add or change some. It supports code reuse and expresses an 'is-a' relationship between a general class and a specialised one.
Example. class SavingsAccount(Account): adds interest handling while reusing deposit and withdraw from Account.
Related: Superclass, Subclass, Method overriding, Polymorphism
- Instance beginner
A single concrete object created from a class. Each one has its own copy of the per-object data while sharing the methods defined by the class. Creating one is done by calling the class like a function.
Example. acct1 = Account('Asha') and acct2 = Account('Ravi') are two separate instances with their own names and balances.
Related: Class, Instance attribute, Constructor, Object
- Instance attribute beginner
A piece of data stored on one specific object, usually assigned inside __init__ through self. Each object has its own value, so changing it on one object does not affect the others.
Example. self.balance = 0 in __init__ gives every Account its own balance; depositing to one leaves the rest unchanged.
Related: Class attribute, Attribute, self, Instance
- Instance method beginner
The ordinary kind of method in a class, whose first parameter receives the specific object it is called on. It can read and change that object's data and the class's shared data.
Example. def area(self): return self.w * self.h uses this rectangle's own width and height.
Related: Class method, Static method, self, Method
- Iterable beginner
Any object that can supply its items one at a time, such as a list, string, dictionary or file. It works with for loops and functions like sum(). Technically, it has an __iter__ method returning an iterator.
Example. A list of pincodes, a string and a range are all iterables you can loop over.
Related: Iterator, Iterator protocol, Generator, for loop
- Iterator intermediate
An object that produces the next item each time next() is called and raises StopIteration when items run out. It remembers its place, so it can be used once, and it makes lazy processing of large data possible.
Example. it = iter([10, 20]); next(it) gives 10, next(it) gives 20, and another next(it) raises StopIteration.
Related: Iterable, Iterator protocol, Generator, StopIteration
- Iterator protocol advanced
The rule set that lets objects work in for loops: an iterable defines __iter__ returning an iterator, and the iterator defines __next__ to return each item and raise StopIteration at the end.
Example. A class with __iter__ returning self and __next__ counting from 1 to 5 can be used directly in for i in Countdown().
Related: Iterator, Iterable, Dunder method, StopIteration
- Lock advanced
A synchronisation tool that lets only one thread or task at a time enter a critical section of code. It prevents corrupted shared data but, if misused, can cause deadlocks or slowdowns.
Example. with lock: counter += 1 ensures two threads never update counter simultaneously.
Related: Race condition, Deadlock, Thread, Context manager
- Metaclass advanced
A class whose instances are themselves classes, controlling how classes are created. The default is type. Metaclasses can register or modify classes automatically, though simpler tools are usually preferred. Most everyday problems are better solved with decorators or inheritance.
Example. class Meta(type) can check at class creation that every subclass defines a required method.
Related: Class, Descriptor, __new__, Decorator
- Method beginner
A function defined inside a class that operates on an object of that class. When called through an object, Python automatically passes that object as the first argument. Methods carry the behaviour of the class and can read or change its data.
Example. class Counter: def add(self): self.n += 1 c.add() increments the counter c.
Related: Self, Class, Instance method, Attribute
- Method overriding intermediate
Defining a method in a subclass with the same name as one in its parent, so the subclass version runs instead. It lets specialised classes change behaviour while keeping the same calling interface.
Example. If Shape.area() raises an error, Circle defines its own area() returning 3.14159 * r ** 2, and calls to circle.area() use that.
Related: Inheritance, Polymorphism, super(), Subclass
- Method resolution order advanced
The linear order in which Python searches a class and its ancestors when looking up an attribute or method. It is computed with the C3 linearisation algorithm so each class appears before its parents and multiple inheritance stays consistent.
Example. Calling C.__mro__ for class C(A, B) shows something like (C, A, B, object), the order Python checks for methods.
Related: Multiple inheritance, super(), Inheritance, Diamond problem
- Mixin advanced
A small class meant to be combined with others through multiple inheritance to add one focused capability, not to stand alone. Mixins let you share behaviour such as logging or serialisation across unrelated classes.
Example. class JSONMixin: def to_json(self): return json.dumps(self.__dict__). Any class inheriting it gains a to_json method.
Related: Multiple inheritance, Inheritance, Composition, Class
- Mocking intermediate
Replacing a real object, such as an API client or database, with a controllable fake during tests. It isolates the code under test, avoids slow or costly calls and lets you simulate errors.
Example. Patching requests.get to return a fixed JSON reply tests parsing code without touching the internet.
Related: unittest.mock, Unit test, Test double, pytest
- Multiple inheritance advanced
A class design where a class lists more than one parent, combining behaviour from each. Python resolves name clashes with the method resolution order. It is powerful but can make code hard to follow if overused.
Example. class Trainer(LoggingMixin, BaseModel) gets logging methods from one parent and model methods from the other.
Related: Mixin, Method resolution order, Diamond problem, Inheritance
- mypy intermediate
A static type checker for Python that reads type hints and reports type mismatches without running the program. It catches bugs early, especially in larger codebases and CI pipelines. It is commonly run as a step in continuous integration checks.
Example. Running mypy on a file that calls total('abc') flags that a string was passed where list[float] was expected.
Related: Type hint, Static analysis, Pyright, CI pipeline
- namedtuple intermediate
A factory in the collections module that creates tuple subclasses whose fields can be read by name as well as by position. They are lightweight, immutable records that make code more readable.
Example. Point = namedtuple('Point', 'x y'); p = Point(3, 4); p.x returns 3.
Related: Dataclass, Tuple, collections module, Immutable
- nonlocal intermediate
A keyword that tells a nested function that an assigned variable refers to one in the nearest enclosing function, not a new local one. It lets inner functions update outer state, such as counters in a closure.
Example. Inside inner(), nonlocal total then total += x updates total from the outer function.
Related: Closure, global, Scope, Decorator
- Object beginner
A value in memory that has an identity, a type and some data, and usually behaviour attached to it. In Python every value, including numbers, functions and classes, is one. Variables are just names pointing at these values.
Example. In x = [1, 2, 3], the list is an object of type list; x is only a name bound to it.
Related: Class, Instance, Type, Reference
- Operator overloading intermediate
Giving your own class custom behaviour for operators such as +, - or == by defining the matching special methods. It lets objects like vectors or money amounts be used with natural arithmetic syntax.
Example. Defining __add__ on Vector lets Vector(1, 2) + Vector(3, 4) produce Vector(4, 6).
Related: Dunder method, __eq__, Polymorphism, Class
- Optional type intermediate
A type hint meaning a value may be of a given type or None, written Optional[int] or int | None. It documents functions that may return nothing and prompts callers to handle the missing case.
Example. def find_user(id) -> str | None: returns a name or None if the id is not found.
Related: Union type, Type hint, None, mypy
- Package beginner
A folder of Python modules, usually with an __init__.py file, that groups related code under one importable name. The word is also used for a distributable project installed with pip.
Example. A folder mytools with __init__.py and utils.py lets you write from mytools import utils.
Related: Module, __init__.py, Import, pyproject.toml
- Parallelism intermediate
Running several computations at literally the same time on multiple processor cores. It speeds up CPU-heavy work and, in Python, is usually achieved with separate processes. It needs multiple cores, and is distinct from merely interleaving tasks.
Example. Using four cores to process four image batches at once takes about a quarter of the sequential time.
Related: Concurrency, Multiprocessing, Global Interpreter Lock, Thread
- Parametrized test intermediate
A test written once and run repeatedly with different input and expected-output pairs. In pytest it uses @pytest.mark.parametrize, reducing duplicated tests and covering edge cases neatly. Each combination is reported as its own test result.
Example. @pytest.mark.parametrize('x,y', [(1, 2), (5, 6)]) def test_inc(x, y): assert inc(x) == y runs twice.
Related: pytest, Fixture, Unit test, Edge case
- pip beginner
Python's standard package installer, which downloads packages from the Python Package Index and installs them, along with their dependencies, into the current environment. It also lists, upgrades and removes packages.
Example. pip install requests fetches and installs the requests library; pip list shows what is installed.
Related: PyPI, Virtual environment, requirements.txt, Dependency
- Poetry intermediate
A tool for managing Python projects that handles dependency resolution, virtual environments, lock files and packaging in one workflow, configured through pyproject.toml. It aims to make dependency handling and publishing to a package index a single tool's job.
Example. poetry add pandas installs pandas, updates pyproject.toml and records exact versions in poetry.lock.
Related: Lock file, pyproject.toml, Virtual environment, uv
- Polymorphism intermediate
The ability to use different kinds of objects through the same interface, with each supplying its own behaviour. Calling one method name on different objects produces behaviour suited to each type.
Example. for shape in shapes: shape.area() works whether the item is a Circle or Rectangle, each computing its own area.
Related: Duck typing, Method overriding, Inheritance, Abstract base class
- Property intermediate
A built-in feature that lets a method be read and set like a plain attribute, using the @property decorator. It allows validation or computed values while keeping simple attribute syntax for callers.
Example. @property def area(self): return self.w * self.h lets you write rect.area without parentheses.
Related: Descriptor, Encapsulation, Decorator, Attribute
- Protocol advanced
A typing feature that defines an interface by the methods an object has, so any class with them is accepted without inheriting. It brings duck typing into static checking and is called structural subtyping.
Example. class Readable(Protocol): def read(self) -> str: ... accepts any object with a matching read method.
Related: Duck typing, Interface, Type hint, Abstract base class
- Pydantic intermediate
A widely used Python library that validates and converts data according to type hints, defining models as classes. It is popular in web APIs and for parsing LLM structured outputs into checked objects.
Example. class User(BaseModel): age: int; User(age='25') converts the string to 25, while age='abc' raises a validation error.
Related: Type hint, Dataclass, Data validation, FastAPI
- pyproject.toml intermediate
The standard configuration file for Python projects, in TOML format. It declares the build system, project metadata and dependencies, and holds settings for tools like pytest and formatters. Modern packaging tools all read it, replacing older setup files.
Example. A [project] section with name = 'mytool' and dependencies = ['requests'] describes a package for building and installing.
Related: Package, Build backend, pip, Poetry
- pytest beginner
A popular Python testing framework that finds functions named test_* , runs them, and reports failures with detailed output. It uses plain assert statements and offers fixtures, parametrisation and plugins.
Example. Saving def test_total(): assert total([1, 2]) == 3 in test_calc.py and running pytest executes it.
Related: Unit test, Fixture, Parametrized test, Assertion
- Relative import intermediate
An import written with leading dots that names a module by its position relative to the current package, such as from . import utils. It keeps a package's internal imports working when the package is renamed.
Example. Inside pkg/model.py, from .layers import Dense imports layers.py from the same package.
Related: Absolute import, Package, Module, Import
- requirements.txt beginner
A plain text file listing the packages a project needs, one per line, often with version pins. Running pip install -r on it recreates the same set of dependencies on another machine.
Example. A file containing numpy==1.26.4 and pandas>=2.0 lets a teammate run pip install -r requirements.txt.
Related: pip, Dependency, Version pinning, Virtual environment
- self beginner
By convention, the name of the first parameter of an instance method. It receives the object the method was called on, so the method can read and modify that object's own data. It is a naming convention, not a keyword.
Example. In def deposit(self, amt): self.balance += amt, self is whichever account called deposit.
Related: Method, Instance attribute, Constructor, Class
- Static method intermediate
A function placed inside a class for organisation but which receives neither the object nor the class automatically. Marked with @staticmethod, it behaves like a plain function that lives in the class's namespace.
Example. @staticmethod def is_valid_pan(text): ... checks a string format and needs no object data.
Related: Class method, Instance method, Decorator, Class
- StopIteration intermediate
The exception an iterator raises when it has no more items. A for loop catches it silently to end the loop, and generators raise it automatically when their function body finishes.
Example. Calling next() on an exhausted iterator raises StopIteration, which is how for knows to stop.
Related: Iterator, Generator, Exception, Iterator protocol
- Subclass intermediate
A class that inherits from another class, gaining its behaviour and adding or changing parts. Objects of a subclass can be used wherever the parent class is expected. It is the counterpart of a parent class in an inheritance relationship.
Example. class ElectricCar(Car) is a subclass; an ElectricCar object still answers to Car methods like drive().
Related: Superclass, Inheritance, Method overriding, isinstance
- super() intermediate
A built-in that returns a proxy for the next class in the method resolution order, letting a subclass call a parent's version of a method. It is most often used to run the parent's __init__ before adding extra setup.
Example. def __init__(self, name, salary): super().__init__(name); self.salary = salary reuses the parent's name handling.
Related: Inheritance, Method resolution order, Method overriding, __init__
- Superclass intermediate
The existing class that another class is built upon and inherits from. It holds the shared attributes and behaviour, also called a parent or base class, which its subclasses reuse or refine.
Example. In class Dog(Animal), Animal is the superclass and supplies methods such as eat().
Related: Subclass, Inheritance, super(), Base class
- Task advanced
An asyncio object that wraps a coroutine and schedules it to run on the event loop in the background. It lets several coroutines progress together and lets you check or cancel them.
Example. t = asyncio.create_task(download(url)) starts the download running while the code continues.
Related: Coroutine, Event loop, asyncio, Future
- Threading intermediate
Python's threading module for running several threads in one process. Because of the interpreter lock, it speeds up input and output waiting tasks, not CPU-bound number crunching. It is simplest when threads share little mutable data.
Example. Starting ten threads to call an API for ten different cities in a Python script so requests overlap.
Related: Thread, Global Interpreter Lock, Multiprocessing, asyncio
- Type hint beginner
An optional annotation stating the expected type of a variable, parameter or return value. Python does not enforce it at run time, but editors and checkers use it to catch bugs and document intent.
Example. def total(prices: list[float]) -> float: says total takes a list of floats and returns a float.
Related: Type annotation, mypy, Generic, Optional type
- TypeVar advanced
A construct from the typing module that creates a placeholder type used to link types across a signature. It expresses that the output type depends on the input type. Together with Generic it underpins reusable, type-safe helpers.
Example. T = TypeVar('T'); def first(xs: list[T]) -> T: tells checkers that first on a list of strings returns a string.
Related: Generic, Type hint, mypy, Protocol
- Union type intermediate
A type hint stating that a value may be one of several types, written Union[int, str] or int | str. It documents flexible parameters and lets checkers verify each case is handled.
Example. def parse(x: int | str) -> int: accepts a number or a numeric string.
Related: Optional type, Type hint, Literal type, mypy
- Unit test beginner
A small automated check that runs one piece of code, such as a function, in isolation and verifies its result against an expected value. Suites of them catch regressions when code changes.
Example. assert add(2, 3) == 5 is a unit test checking that add returns 5.
Related: pytest, Test case, Assertion, Mocking
- unittest.mock advanced
A standard library module providing Mock objects and the patch tool for replacing parts of a program during tests and recording how they were called. It supports assertions such as assert_called_once_with.
Example. with patch('app.send_sms') as m: run(); m.assert_called_once() checks that an SMS was attempted without sending one.
Related: Mocking, pytest, Unit test, Test double
- uv intermediate
A fast Python package and project manager written in Rust that can install packages, create virtual environments and manage lock files, offering a quicker replacement for common pip and venv workflows.
Example. uv pip install requests installs the package much like pip but with a different, faster implementation.
Related: pip, Virtual environment, Lock file, Poetry
- venv beginner
The standard library module and command that creates virtual environments. Running python -m venv name makes a folder with an isolated interpreter setup and pip. It ships with Python, so no separate installation is needed for basic isolation.
Example. python -m venv .venv then source .venv/bin/activate on Linux or macOS, or .venv\Scripts\activate on Windows.
Related: Virtual environment, pip, conda, Activation
- Version pinning intermediate
Specifying exact package versions, such as pandas==2.1.4, so installs behave identically over time. It prevents surprise breakages from new releases but needs occasional deliberate upgrades. Teams pin versions so results, such as model behaviour, stay reproducible.
Example. Pinning scikit-learn==1.4.2 ensures a trained model file loads the same way in production as in development.
Related: requirements.txt, Semantic versioning, Lock file, Dependency
- Virtual environment beginner
An isolated folder holding its own Python interpreter link and installed packages for one project. It prevents version clashes between projects and keeps the system Python clean. Deleting the folder removes the environment without touching other projects.
Example. python -m venv .venv creates one; after activating it, pip install pandas affects only this project.
Related: venv, pip, requirements.txt, Dependency
- Wheel intermediate
A built, ready-to-install package format for Python, stored as a .whl file. Installing one is faster than building from source and needs no compiler, which matters for packages with compiled code.
Example. pip install numpy usually downloads a wheel matching your platform and Python version.
Related: Package, pip, PyPI, Source distribution
- with statement beginner
A statement that runs a block inside a context manager, calling its setup code on entry and its cleanup code on exit, even when exceptions occur. It replaces manual try/finally patterns for resources.
Example. with open('log.txt', 'w') as f: f.write('done') ensures the file is closed afterwards.
Related: Context manager, __enter__ and __exit__, Exception, File handling
- yield intermediate
A keyword that turns a function into a generator. When reached, it hands a value back to the caller and freezes the function, so a later request resumes right after it with all variables intact.
Example. def read_lines(f): for line in f: yield line.strip() returns cleaned lines one by one from a huge file.
Related: Generator, yield from, Lazy evaluation, Coroutine
- yield from advanced
A statement that delegates to another iterable or generator, yielding each of its values in turn and passing back its return value. It simplifies chaining generators and was a stepping stone towards async syntax.
Example. def flatten(lists): for sub in lists: yield from sub produces every item from every inner list.
Related: yield, Generator, Iterator, Coroutine