Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

API reference

Python API reference

modern Python for backend and scripting

Identifiers
163
With full guides
133
Types
6

Topics covered

  • Comprehensions
  • Decorators
  • Generators & yield
  • Type hints
  • async / await
  • Dataclasses
  • Context managers
  • Packaging & venv

Class

NameWhat it does
listlist is Python’s mutable sequence type. Create one with a literal, comprehension, or list(iterable); construction preserves the iterable’s item order.
dictdict is Python’s mutable mapping type, associating hashable keys with arbitrary values. It supports construction from mappings, key-value pairs, and keyword arguments, plus dynamic key, value, and item views.
setset creates a mutable, unordered collection of distinct hashable objects. It supports membership, iteration, deduplication, and set operations.
TypedDictTypedDict describes the expected keys and value types of dictionary-shaped data for static type checking. At runtime, values remain ordinary dictionaries and the constraints are not enforced by Python itself.
tupletuple is Python’s immutable sequence type. Create tuples with comma-separated values or tuple(iterable); they support common sequence operations and can hold heterogeneous or homogeneous data.
strstr is Python’s immutable Unicode text type and sequence of code points. Its constructor creates printable text from objects or decodes bytes when an encoding is supplied.
intint() creates an integer from a number or string, or returns 0 with no arguments. For strings, base controls parsing, including automatic prefix-based parsing with base=0.
EnumEnum defines a fixed set of symbolic names associated with values. Its members support identity comparison, iteration, and lookup by value or name.
floatfloat constructs a floating-point number from a number or string. It also accepts no argument, returning 0.0.
boolbool() converts an object through Python’s standard truth-testing procedure and returns True or False. With no argument it returns False; bool is an int subclass with only the two instances True and False.
frozensetfrozenset creates an immutable, hashable set of unique elements. It is useful as a dictionary key or as an element of another set when the collection itself must remain fixed.
bytesbytes is Python’s immutable binary sequence type. It stores individual byte values as integers from 0 through 255 and can be created from literals, iterable data, or encoded text.
bytearrayClass
complexcomplex() converts a string or number to a complex number, or constructs one from real and imaginary parts. It also supports documented numeric conversion protocols for general objects.
objectClass
typetype() returns an object's runtime type, or creates a new type when called with three arguments. Its one-argument result generally matches the object's __class__.
memoryviewClass
defaultdictdefaultdict is a dict subclass that creates and stores a value for an absent key by calling a configured zero-argument factory. It is useful for grouping, counting, and collecting distinct values without pre-initializing every key.
CounterCounter is a dict subclass for tallying hashable objects. It maps each element to its count and supports specialized counting, comparison, and multiset operations.
OrderedDictOrderedDict is a dict subclass for mappings where changing entry order is important. It adds endpoint reordering and configurable-end removal operations beyond ordinary dictionary behavior.
dequecollections.deque is a double-ended, list-like container with efficient appends and pops at either end. An optional maxlen bounds its size and automatically discards items from the opposite end when full.
namedtuplenamedtuple() builds tuple subclasses with readable named fields. The resulting records remain indexable and iterable like tuples while also supporting attribute access.
ChainMapChainMap creates one dictionary-like view over multiple mappings. Lookups use the first matching mapping, while mutations target only the first mapping.

Function

NameWhat it does
printWrites zero or more objects to a text stream, separating them with sep and ending with end. The destination and flushing behavior can be customized with keyword-only arguments.
lenFunction
rangeFunction
enumerateenumerate() pairs each item from an iterable with an incrementing count. The count starts at 0 by default or at the supplied start value.
openFunction
zipzip() iterates over multiple iterables in parallel and yields tuples of corresponding elements. It is lazy and can optionally require equal input lengths with strict=True.
mapmap() returns an iterator that applies a function to items from one or more iterables. With multiple inputs, it processes corresponding items in parallel and can require equal lengths with strict=True.
filterfilter() constructs an iterator containing elements from an iterable that pass a function's truth test. With None as the function, it removes false-valued elements.
sortedFunction
reversedReturns an iterator that traverses a supported object in reverse order. It does not itself create or mutate a reversed collection.
sumsum() adds the items of an iterable from left to right, starting with an optional initial value. It returns the resulting total and is intended primarily for numeric items.
minReturns the smallest item from an iterable or the smallest among multiple arguments. Use key for derived comparisons and default to handle an empty iterable.
maxmax() returns the largest item from an iterable or the largest among two or more positional arguments. Use key to control ordering and default to handle an empty iterable.
absabs() returns the absolute value of a number. Complex inputs produce their magnitude, and objects can define custom behavior with __abs__().
roundround() rounds a number to a selected decimal precision, or to the nearest integer when ndigits is omitted. Ties for built-in numeric types use round-half-to-even.
powpow() raises a base to an exponent, optionally reducing the result modulo a third argument. Its two-argument form is equivalent to the ** operator, while the three-argument form is optimized for modular exponentiation.
divmoddivmod() returns a pair containing the quotient and remainder for two non-complex numbers. For integers, it is equivalent to (a // b, a % b), while floating-point inputs have documented rounding nuances.
allReturns True when every element in an iterable is truthy, and also for an empty iterable. It short-circuits at the first false element.
anyFunction
isinstanceTests whether an object is an instance of a type, accepted subclass, tuple of types, or Union Type. It returns a Boolean and supports subclass-aware checks.
issubclassFunction
idid() returns an integer identity for an object. It remains unique and constant during that object's lifetime, but values may be reused by objects whose lifetimes do not overlap.
hashhash() returns an integer hash value for an object that provides one. Python uses hashes to speed dictionary-key lookup, and equal numeric values share the same hash even across types.
reprrepr(object) returns a printable string representation of an object. For many types it aims to produce text that can recreate an equal-valued object with eval(), while other objects use a descriptive fallback.
formatformat() converts a value to a formatted string representation. Its optional format specification controls presentation according to the value’s type.
inputFunction
iteriter() returns an iterator for an iterable object, or repeatedly invokes a callable until its result equals a supplied sentinel. It supports both protocol-based iteration and callable-driven iteration.
nextRetrieves one item from an iterator. An optional default value replaces StopIteration when the iterator is exhausted.
getattrgetattr() retrieves an attribute using a string name. It can return a fallback for missing attributes or raise AttributeError when no fallback is supplied.
setattrFunction
hasattrChecks whether an object has an attribute with a specified string name. It returns True when the lookup succeeds and False when it raises AttributeError.
delattrdelattr() deletes a named attribute from an object when the object permits it. Because the name is supplied as a string, it supports attribute deletion chosen dynamically at runtime.
varsvars() returns an object's __dict__ mapping, or behaves like locals() when called without an argument. It raises TypeError for an object that lacks __dict__.
dirdir() lists names in the current local scope or, when given an object, attempts to list its available attributes. It is primarily an interactive discovery aid and can be customized through __dir__().
callableTests whether an object appears callable. Classes, functions, and instances with __call__() can return True, but a True result does not guarantee that invocation will succeed.
evaleval() evaluates a Python expression from source text or a code object and returns its result. Optional global and local namespaces control name resolution.
execexec dynamically executes Python statements from a string or code object. Explicit namespace mappings let you control where names are resolved and stored.
compilecompile() turns source text, bytes, or an AST into a code object or AST object. The mode selects statement-sequence, expression, or interactive-statement compilation.
globalsglobals() returns the dictionary representing the current module namespace. In a function, that namespace belongs to the module where the function was defined.
localsFunction
superFunction
sliceslice creates a reusable object describing a range of indices. Sequences can consume it for indexed access, and Python also creates such objects from slicing syntax.

Type Alias

NameWhat it does
Listtyping.List[T] describes lists containing elements of type T and can be used in type aliases. It is deprecated in current Python documentation; use built-in list[T] for new code.
DictType Alias
TupleType Alias
OptionalOptional[X] describes a value that may be either X or None. In modern Python, X | None is the equivalent spelling; Optional does not merely mean that an argument has a default.
UnionA union type annotation allows a value to match one of several types. Modern Python uses X | Y; this is equivalent to Union[X, Y], whose shorthand is recommended.
AnyType Alias
CallableCallable describes the signature of a function or other callable object: its parameter types and return type. Use collections.abc.Callable in modern annotations; typing.Callable is deprecated.
Iterablecollections.abc.Iterable[T] annotates an object that can provide values of type T one at a time. It is the modern replacement for the deprecated typing.Iterable alias.
IteratorIterator[T] annotates an iterator that yields values of type T. Modern Python code should use collections.abc.Iterator[T], while typing.Iterator remains as a compatibility form.
GeneratorGenerator is a generic type alias for annotating generator functions. Its parameters describe yielded values, values accepted by send(), and the final return value.
TypeVarTypeVar creates a named type variable for generic functions, classes, and type aliases. Static type checkers use it to preserve relationships between types, while Python does not enforce the annotation at runtime.
GenericA generic type alias is a reusable name for a type expression parameterized by one or more type variables. Modern Python declares its parameters in brackets after the alias name; static type checkers use them to form specialized aliases.
Protocoltyping.Protocol defines interfaces for structural subtyping. Static type checkers can accept any class that supplies the protocol’s declared members, even without explicit inheritance.
Literaltyping.Literal expresses that an annotated value must equal one of a specified set of literals. It is useful for statically checking constrained strings, numbers, booleans, and similar fixed choices.
FinalType Alias
AnnotatedType Alias

Const

NameWhat it does
defdef defines a named user-defined function, optionally with decorators, parameters, and a return annotation. Its indented body runs when the function is called.
classThe class statement defines a class object from a name, optional type parameters and bases, and an indented suite. A missing base list defaults to object; multiple bases enable multiple inheritance.
lambdaA lambda expression creates an anonymous function object from an optional parameter list and one expression. Calling it returns the value produced by that expression.
asyncasync is Python’s syntax family for coroutine functions and asynchronous control flow. It introduces async def, async for, and async with; await is used within coroutine bodies to suspend execution until an awaitable completes.
awaitawait suspends a coroutine until an awaitable completes, then yields that awaitable’s result. It is valid only inside a coroutine function.
yieldConst
returnThe return statement exits the current function call and provides its result. With no expression, it returns None; generator and asynchronous-generator functions have specialized completion rules.
ifPython’s if statement conditionally executes one suite. It checks the if and optional elif conditions in order, running the first matching suite or an optional else fallback.
elifelif introduces an additional condition in an if statement. Conditions are checked in order, and only the suite for the first true condition executes.
elseelse supplies a fallback or successful-completion branch in Python compound statements. Its meaning depends on whether it follows if, a loop, or try.
forThe for statement repeats a suite for each element produced by a sequence or other iterable. It binds each element to a target and supports break, continue, and an optional else clause.
whileThe while statement repeatedly executes an indented suite while its condition is true. An optional else suite runs when the condition becomes false, but not when break exits the loop.
tryThe try statement runs potentially failing code and can respond with matching except handlers. Optional else handles success-only work, while finally provides cleanup that runs regardless of the outcome.
exceptConst
finallyPython’s finally clause runs cleanup code after a try statement, regardless of whether an exception occurs. It also runs before return, break, or continue leaves the try statement.
withConst
importThe import statement finds and initializes modules as needed, then binds modules or selected names in the current namespace. It supports aliases, qualified module paths, relative imports, and from ... import ... forms.
fromfrom is part of Python’s import statement: it selects names from a module and binds them in the current namespace, optionally under aliases. Leading dots enable package-relative imports.
globalThe global statement makes listed names refer to the module’s top-level namespace throughout the current scope. It is mainly needed when code inside a function assigns to a module-level variable.
nonlocalThe nonlocal statement lets nested code rebind names from an enclosing function scope. It requires each name to already exist in a nonlocal enclosing scope and selects the nearest matching binding.
passpass is Python's no-op statement. It supplies a syntactically required statement when a function, class, or other body intentionally has nothing to execute.
breakbreak exits the nearest enclosing for or while loop immediately. It is a statement rather than a callable value.
continuecontinue skips the rest of the current iteration and starts the next cycle of the nearest enclosing for or while loop. It has no arguments and is valid only in an appropriate loop context.
raisePython’s raise statement explicitly raises an exception, re-raises the active exception, or chains a new exception to an existing cause.
assertassert performs a debugging check and raises AssertionError when its condition is false. An optional expression supplies the failure value, but optimized execution can disable assertions.
deldel removes a name binding or deletes an item, attribute, or slice. It acts on targets and does not return a value.
matchThe match statement performs structural pattern matching by testing a subject against ordered case patterns. It executes the first successful case, optionally subject to a guard.
casecase introduces a pattern-matching block inside Python’s match statement. Cases are checked in order, can bind matched values, and may include guards or a wildcard fallback.

Decorator

NameWhat it does
dataclassDecorator
propertyThe property decorator exposes method-based behavior through normal attribute syntax. It can provide controlled reading, writing, deletion, and documentation for an attribute.
staticmethod@staticmethod turns a class-defined function into a static method that receives no implicit instance or class argument. It can be called through either the class or an instance.
classmethod@classmethod turns a method into one whose implicit first argument is the class. It may be called through a class or instance, and subclass calls receive the subclass.

Module

NameWhat it does
asyncioModule
functoolsPython’s functools module provides higher-order-function tools for adapting, decorating, caching, reducing, and dispatching callable objects. It includes utilities such as cache, lru_cache, partial, reduce, singledispatch, wraps, and update_wrapper.
jsonPython’s json module encodes compatible Python data as JSON and decodes JSON back into Python objects. It supports strings, file-like objects, formatting options, hooks, and a command-line interface.
pathlibpathlib supplies object-oriented filesystem path classes. Use Path for platform-aware filesystem operations and pure path classes for calculations that do not access the filesystem.
typingThe typing module provides standard constructs for annotating Python code with type information. Type hints guide third-party tools such as type checkers, IDEs, and linters, but Python does not enforce them at runtime.
pytestModule
abcModule
collectionsPython’s collections module provides specialized container types as alternatives to built-in dict, list, set, and tuple. It includes tools for queues, counting, layered mappings, named records, default values, and container subclassing.
itertoolsModule
osPython’s os module provides portable interfaces to operating-system functionality, including environment variables, process parameters, files, directories, and file descriptors. Use os.path for pathname manipulation and specialized modules for higher-level file operations.
sysPython’s always-available sys module exposes interpreter-maintained values and runtime-oriented functions. It is commonly used for command-line arguments, executable and version details, loaded modules, import paths, and object-size inspection.
reModule
datetimePython’s datetime module supplies standard-library types for dates, times, combined timestamps, durations, and time zones. It supports arithmetic, field extraction, conversion, and explicit string formatting.
mathPython's math module provides common real-number mathematical functions and constants, including floating-point, trigonometric, logarithmic, summation, distance, and number-theoretic operations. Use cmath instead when calculations require complex numbers.
randomPython's random module supplies pseudo-random values for distributions, integer ranges, and sequence operations. Its default Mersenne Twister generator is not suitable for security-sensitive randomness.
dataclassesThe dataclasses module generates common methods for classes whose fields are declared with type annotations. Its decorator and helper functions support initialization, comparison, immutability, conversion, inspection, and dynamic class creation.
enumPython's enum module defines enumerations: named members associated with values. Enumerations support class or functional construction, iteration, lookup by value, and lookup by name.
contextlibPython’s contextlib module provides helpers for building, composing, and adapting synchronous or asynchronous context managers. It simplifies deterministic setup and cleanup around with and async with blocks.
copyPython's copy module provides shallow and deep copying for compound objects. Shallow copies share nested objects, while deep copies recursively duplicate them.
picklepickle serializes Python object hierarchies into binary streams and reconstructs them later. It is Python-specific and must only be used with trusted data because unpickling can execute code.
sqlite3Python's sqlite3 module provides a DB-API 2.0 interface for working with SQLite databases. It supports file-backed or in-memory databases and can also run as a simple SQLite shell.
csvPython’s csv module reads and writes tabular data in CSV format, supporting both sequence rows and dictionary rows. Dialects and formatting parameters adapt it to different CSV conventions.
loggingPython's logging module provides a flexible event-logging system for applications and libraries. Loggers create records that handlers route, filters select, and formatters lay out.
subprocessThe subprocess module launches external programs, connects to their standard streams, and reports their completion status. Use run() for typical commands and Popen for advanced process management.
threadingModule
multiprocessingmultiprocessing provides process-based concurrency through an API resembling threading. It can use multiple processors and includes Pool for distributing a function across input values.
urlliburllib is a standard-library package that groups modules for opening, parsing, and otherwise working with URLs. Its modules also cover request errors and robots.txt parsing.
unittestPython’s unittest module provides a standard framework for automating unit tests, sharing setup and cleanup, grouping tests, and reporting results. Tests are commonly organized as TestCase instances and run through the module’s command-line interface.
argparseargparse builds command-line interfaces from declared arguments and options. It parses input into a Namespace and automatically provides help, usage, and invalid-input errors.
timePython’s time module provides clocks, sleeping, epoch-based conversions, and formatting utilities. Use wall-clock functions for timestamps and monotonic or performance counters for measuring elapsed durations.
decimalPython’s decimal module provides correctly rounded decimal arithmetic with configurable precision, rounding, exponent limits, and signal handling. It is designed for exact decimal-style and controlled rounded calculations.
statisticsPython’s statistics module provides standard-library functions for averages, central tendency, spread, relationships, quantiles, and normal distributions over numeric data.
heapqheapq provides a list-based priority queue using a min-heap. It supports efficiently adding items and retrieving the smallest item.
bisectThe bisect module finds insertion points in sorted sequences and provides helpers for inserting values without resorting the list. Left and right variants control whether duplicates are placed before or after existing equal values.
hashlibPython’s hashlib module provides a common interface for generating digests with standard hash algorithms. Create a hash object, supply bytes-like data, and read the result as bytes or hexadecimal text.
uuidPython’s uuid module provides immutable UUID objects and functions for generating UUIDs across RFC 9562 versions. It supports parsing and constructing UUIDs from text, bytes, fields, or integers.
ioPython’s io module provides the core stream interfaces for text, binary, and raw input/output. It also supplies in-memory file-like streams such as StringIO and BytesIO.
shutilshutil provides high-level filesystem operations for copying, moving, deleting, and archiving files and directory trees. It complements os by simplifying common multi-file and directory tasks.
globThe glob module finds filesystem pathnames with shell-style patterns such as *, ?, and []. Use glob() for a list or iglob() for lazy iteration, with optional recursive searching via **.
__init____init__ is a special method that initializes a new instance when its class is called. Arguments supplied during instantiation are passed to it, allowing each object to start with customized state.
__str____str__(self) defines an object's informal, human-readable string representation. Python uses it through str(), print(), and default formatting, and the method must return a str.
__repr____repr__ defines an object's official string representation for repr(). Make it information-rich and unambiguous, ideally resembling Python code that can recreate the value.
__len____len__ implements the built-in len() operation for an object. It should return a non-negative integer, and a zero result supplies falsey behavior when __bool__ is not defined.
__iter____iter__ is the special method Python calls when it needs an iterator for a container. Implement it to return an iterator over the container’s contents; mappings conventionally iterate over keys.
__next____next__() is the iterator protocol method that returns the next item. It must raise StopIteration when the iterator is exhausted.
__enter__Module
__exit____exit__ is the context-manager hook Python invokes when leaving a with block. It receives exception details when the block fails and can suppress the exception by returning a true value.
__call__Defining __call__ on a class makes its instances callable like functions. Calling an instance dispatches to the class’s __call__ method with the instance and supplied arguments.
__getitem__Module
__setitem____setitem__ implements assignment through subscription syntax such as obj[key] = value. It is used by mutable mappings and sequences to update, add, or replace stored elements.

Search across every package and filter by type in your dashboard.

Start learning