PyDocs

Quick Reference

Quickref for the Python Standard Library

The most used parts of Python, grouped by purpose. Click any name for its docs and examples.

Simple Values

Numbers

Simple Values

Arithmetic

Numbers > Arithmetic

abs
Return the absolute value of the argument.
divmod
Return the tuple (x//y, x%y).
pow
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
round
Round a number to a given precision in decimal digits.
sum
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
min
With a single iterable argument, return its smallest item.
max
With a single iterable argument, return its biggest item.

Convert

Numbers > Convert

int
Convert a number or string to an integer, or return 0 if no arguments are given.
float
Convert a string or number to a floating-point number, if possible.
complex
Create a complex number from a string or numbers.
bin
Return the binary representation of an integer.
oct
Return the octal representation of an integer.
hex
Return the hexadecimal representation of an integer.
int.from_bytes
Return the integer represented by the given array of bytes.
int.to_bytes
Return an array of bytes representing an integer.
float.as_integer_ratio
Return a pair of integers, whose ratio is exactly equal to the original float.
float.is_integer
Return True if the float is an integer.

Math

Numbers > Math

math.floor
Return the floor of x as an Integral.
math.ceil
Return the ceiling of x as an Integral.
math.trunc
Truncates the Real x to the nearest Integral toward 0.
math.sqrt
Return the square root of x.
math.isqrt
Return the integer part of the square root of the input.
math.exp
Return e raised to the power of x.
math.log
Return the logarithm of x to the given base.
math.log10
Return the base 10 logarithm of x.
math.log2
Return the base 2 logarithm of x.
math.isclose
Determine whether two floating-point numbers are close in value.
math.gcd
Greatest Common Divisor.
math.lcm
Least Common Multiple.
math.comb
Number of ways to choose k items from n items without repetition and without order.
math.perm
Number of ways to choose k items from n items without repetition and with order.
math.prod
Calculate the product of all the elements in the input iterable.
math.fsum
Return an accurate floating-point sum of values in the iterable seq.
math.pi
The mathematical constant π = 3.141592…, to available precision.
math.inf
A floating-point positive infinity.
math.nan
A floating-point “not a number” (NaN) value.
math.isnan
Return True if x is a NaN (not a number), and False otherwise.
math.isinf
Return True if x is a positive or negative infinity, and False otherwise.

Exact

Numbers > Exact

decimal.Decimal
Construct a new Decimal object.
decimal.getcontext
Get the current default context.
fractions.Fraction
This class implements rational numbers.

Random

Numbers > Random

random.random
random() -> x in the interval [0, 1).
random.randint
Return random integer in range [a, b], including both end points.
random.randrange
Choose a random item from range(stop) or range(start, stop[, step]).
random.uniform
Get a random number in the range [a, b) or [a, b] depending on rounding.
random.choice
Choose a random element from a non-empty sequence.
random.choices
Return a k sized list of population elements chosen with replacement.
random.sample
Chooses k unique random elements from a population sequence.
random.shuffle
Shuffle list x in place, and return None.
random.seed
Initialize internal state from a seed.

Statistics

Numbers > Statistics

statistics.mean
Return the sample arithmetic mean of data.
statistics.median
Return the median (middle value) of numeric data.
statistics.mode
Return the most common data point from discrete or nominal data.
statistics.stdev
Return the square root of the sample variance.
statistics.variance
Return the sample variance of data.
statistics.quantiles
Divide *data* into *n* continuous intervals with equal probability.

Booleans

Simple Values

Create

Booleans > Create

bool
Returns True when the argument is true, False otherwise.

Test

Booleans > Test

all
Return True if bool(x) is True for all values x in the iterable.
any
Return True if bool(x) is True for any x in the iterable.
callable
Return whether the object is callable (i.e., some kind of function).
isinstance
Return whether an object is an instance of a class or of a subclass thereof.
issubclass
Return whether 'cls' is derived from another class or is the same class.

Strings

Simple Values

Create

Strings > Create

str
Create a new string object from the given object.
repr
Return the canonical string representation of the object.
ascii
Return an ASCII-only representation of an object.
chr
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
ord
Return the ordinal value of a character.
format
Return type(value).__format__(value, format_spec)
str.format
Return a formatted version of the string, using substitutions from args and kwargs.
str.format_map
Return a formatted version of the string, using substitutions from mapping.

Test

Strings > Test

str.startswith
Return True if the string starts with the specified prefix, False otherwise.
str.endswith
Return True if the string ends with the specified suffix, False otherwise.
str.isdigit
Return True if the string is a digit string, False otherwise.
str.isnumeric
Return True if the string is a numeric string, False otherwise.
str.isalpha
Return True if the string is an alphabetic string, False otherwise.
str.isalnum
Return True if the string is an alpha-numeric string, False otherwise.
str.isspace
Return True if the string is a whitespace string, False otherwise.
str.isupper
Return True if the string is an uppercase string, False otherwise.
str.islower
Return True if the string is a lowercase string, False otherwise.
str.isidentifier
Return True if the string is a valid Python identifier, False otherwise.

Search

Strings > Search

str.find
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
str.rfind
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end].
str.index
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end].
str.count
Return the number of non-overlapping occurrences of substring sub in string S[start:end].

Transform

Strings > Transform

str.upper
Return a copy of the string converted to uppercase.
str.lower
Return a copy of the string converted to lowercase.
str.casefold
Return a version of the string suitable for caseless comparisons.
str.title
Return a version of the string where each word is titlecased.
str.capitalize
Return a capitalized version of the string.
str.swapcase
Convert uppercase characters to lowercase and lowercase characters to uppercase.
str.replace
Return a copy with all occurrences of substring old replaced by new.
str.strip
Return a copy of the string with leading and trailing whitespace removed.
str.lstrip
Return a copy of the string with leading whitespace removed.
str.rstrip
Return a copy of the string with trailing whitespace removed.
str.removeprefix
Return a str with the given prefix string removed if present.
str.removesuffix
Return a str with the given suffix string removed if present.
str.zfill
Pad a numeric string with zeros on the left, to fill a field of the given width.
str.center
Return a centered string of length width.
str.ljust
Return a left-justified string of length width.
str.rjust
Return a right-justified string of length width.
str.expandtabs
Return a copy where all tab characters are expanded using spaces.
str.translate
Replace each character in the string using the given translation table.
str.maketrans
Return a translation table usable for str.translate().

Split / Join

Strings > Split / Join

str.split
Return a list of the substrings in the string, using sep as the separator string.
str.rsplit
Return a list of the substrings in the string, using sep as the separator string.
str.splitlines
Return a list of the lines in the string, breaking at line boundaries.
str.partition
Partition the string into three parts using the given separator.
str.rpartition
Partition the string into three parts using the given separator.
str.join
Concatenate any number of strings.

Text Tools

Strings > Text Tools

textwrap.dedent
Remove any common leading whitespace from every line in `text`.
textwrap.indent
Adds 'prefix' to the beginning of selected lines in 'text'.
textwrap.fill
Fill a single paragraph of text, returning a new string.
textwrap.wrap
Wrap a single paragraph of text, returning a list of wrapped lines.
textwrap.shorten
Collapse and truncate the given text to fit in the given width.
string.Template
A string class for supporting $-substitutions.
string.ascii_letters
The concatenation of the ascii_lowercase and ascii_uppercase constants described below.
string.digits
The string '0123456789'.
string.punctuation
String of ASCII characters which are considered punctuation characters in the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}…
difflib.get_close_matches
Use SequenceMatcher to return list of the best "good enough" matches.
difflib.unified_diff
Compare two sequences of lines; generate the delta as a unified diff.

Regular Expressions

Simple Values

Match

Regular Expressions > Match

re.match
Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.
re.search
Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found.
re.fullmatch
Try to apply the pattern to all of the string, returning a Match object, or None if no match was found.
re.findall
Return a list of all non-overlapping matches in the string.
re.finditer
Return an iterator over all non-overlapping matches in the string.

Change

Regular Expressions > Change

re.sub
Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replac…
re.subn
Return a 2-tuple containing (new_string, number).
re.split
Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings.
re.escape
Escape special characters in a string.

Compile

Regular Expressions > Compile

re.compile
Compile a regular expression pattern, returning a Pattern object.
re.Pattern
Compiled regular expression object.
re.Match
The result of re.search(), re.prefixmatch(), and re.fullmatch().
re.Match.group
Return subgroup(s) of the match by indices or names.
re.Match.groups
Return a tuple containing all the subgroups of the match, from 1.
re.Match.groupdict
Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
re.IGNORECASE
Perform case-insensitive matching; expressions like [A-Z] will also match lowercase letters.
re.MULTILINE
When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (imm…
re.DOTALL
Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anyth…
re.VERBOSE
This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually sep…

Bytes

Simple Values

Create

Bytes > Create

bytes
Construct an immutable array of bytes from: - an iterable yielding integers in range(256) - a text string encoded using…
bytearray
Construct a mutable bytearray object from: - an iterable yielding integers in range(256) - a text string encoded using …
memoryview
Create a new memoryview object which references the given object.
bytes.fromhex
Create a bytes object from a string of hexadecimal numbers.

Convert

Bytes > Convert

bytes.decode
Decode the bytes using the codec registered for encoding.
str.encode
Encode the string using the codec registered for encoding.
bytes.hex
Create a string of hexadecimal numbers from a bytes object.
base64.b64encode
Encode the bytes-like object s using Base64 and return a bytes object.
base64.b64decode
Decode the Base64 encoded bytes-like object or ASCII string s.
struct.pack
Pack values and return the packed bytes.
struct.unpack
Return a tuple containing values unpacked according to the format string.

Collections

Lists

Collections

Create

Lists > Create

list
Built-in mutable sequence.
range
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
list.copy
Return a shallow copy of the list.

Change

Lists > Change

list.append
Append object to the end of the list.
list.extend
Extend list by appending elements from the iterable.
list.insert
Insert object before index.
list.remove
Remove first occurrence of value.
list.pop
Remove and return item at index (default last).
list.clear
Remove all items from list.
list.sort
Sort the list in ascending order and return None.
list.reverse
Reverse *IN PLACE*.

Inspect

Lists > Inspect

len
Return the number of items in a container.
list.index
Return first index of value.
list.count
Return number of occurrences of value.
sorted
Return a new list containing all items from the iterable in ascending order.
reversed
Return a reverse iterator over the values of the given sequence.
min
With a single iterable argument, return its smallest item.
max
With a single iterable argument, return its biggest item.

Sorted lists

Lists > Sorted lists

bisect.bisect_left
Return the index where to insert item x in list a, assuming a is sorted.
bisect.bisect_right
Return the index where to insert item x in list a, assuming a is sorted.
bisect.insort
Insert item x in list a, and keep it sorted assuming a is sorted.

Tuples

Collections

Create

Tuples > Create

tuple
Built-in immutable sequence.
tuple.count
Return number of occurrences of value.
tuple.index
Return first index of value.
collections.namedtuple
Returns a new subclass of tuple with named fields.
typing.NamedTuple
Typed version of collections.namedtuple.

Dictionaries

Collections

Create

Dictionaries > Create

dict
(key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(*…
dict.fromkeys
Create a new dictionary with keys from iterable and values set to value.
dict.copy
Return a shallow copy of the dict.

Read

Dictionaries > Read

dict.get
Return the value for key if key is in the dictionary, else default.
dict.keys
Return a set-like object providing a view on the dict's keys.
dict.values
Return an object providing a view on the dict's values.
dict.items
Return a set-like object providing a view on the dict's items.

Change

Dictionaries > Change

dict.setdefault
Insert key with a value of default if key is not in the dictionary.
dict.update
If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys()…
dict.pop
If the key is not found, return the default if given; otherwise, raise a KeyError.
dict.popitem
Remove and return a (key, value) pair as a 2-tuple.
dict.clear
Remove all items from the dict.

Specialized

Dictionaries > Specialized

collections.defaultdict
defaultdict(default_factory=None, /, [...]) --> dict with default factory
collections.Counter
Dict subclass for counting hashable items.
collections.Counter.most_common
List the n most common elements and their counts from the most common to the least.
collections.OrderedDict
Dictionary that remembers insertion order
collections.ChainMap
A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view.

Views

Dictionaries > Views

types.MappingProxyType
Read-only proxy of a mapping.

Sets

Collections

Create

Sets > Create

set
Build an unordered collection of unique elements.
frozenset
Build an immutable unordered collection of unique elements.

Change

Sets > Change

set.add
Add an element to a set.
set.discard
Remove an element from a set if it is a member.
set.remove
Remove an element from a set; it must be a member.
set.pop
Remove and return an arbitrary set element.
set.update
Update the set, adding elements from all others.
set.clear
Remove all elements from this set.

Set operations

Sets > Set operations

frozenset.union
Return a new set with elements from the set and all others.
frozenset.intersection
Return a new set with elements common to the set and all others.
frozenset.difference
Return a new set with elements in the set that are not in the others.
frozenset.symmetric_difference
Return a new set with elements in either the set or other but not both.

Test

Sets > Test

frozenset.issubset
Report whether another set contains this set.
frozenset.issuperset
Report whether this set contains another set.
frozenset.isdisjoint
Return True if two sets have a null intersection.

Specialized Containers

Collections

Queues

Specialized Containers > Queues

collections.deque
A list-like sequence optimized for data accesses near its endpoints.
queue.Queue
Create a queue object with a given maximum size.
queue.PriorityQueue
Variant of Queue that retrieves open entries in priority order (lowest first).

Heaps

Specialized Containers > Heaps

heapq.heappush
Push item onto heap, maintaining the heap invariant.
heapq.heappop
Pop the smallest item off the heap, maintaining the heap invariant.
heapq.heapify
Transform list into a heap, in-place, in O(len(heap)) time.
heapq.nlargest
Find the n largest elements in a dataset.
heapq.nsmallest
Find the n smallest elements in a dataset.
heapq.merge
Merge multiple sorted inputs into a single sorted output.

Records

Specialized Containers > Records

dataclasses.dataclass
Add dunder methods based on the fields defined in the class.
dataclasses.field
Return an object to identify dataclass fields.
dataclasses.asdict
Return the fields of a dataclass instance as a new dictionary mapping field names to field values.
dataclasses.replace
Return a new object replacing specified fields with new values.
dataclasses.fields
Return a tuple describing the fields of this dataclass.
typing.TypedDict
A simple typed namespace.

Arrays

Specialized Containers > Arrays

array.array
Return a new array whose items are restricted by typecode, and initialized from the optional initializer value, which m…

Iteration & Functions

Iteration

Iteration & Functions

Basics

Iteration > Basics

iter
Get an iterator from an object.
next
Return the next item from the iterator.
enumerate
Return an enumerate object.
zip
The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip().
range
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
reversed
Return a reverse iterator over the values of the given sequence.
sorted
Return a new list containing all items from the iterable in ascending order.
len
Return the number of items in a container.

Transform

Iteration > Transform

map
Make an iterator that computes the function using arguments from each of the iterables.
filter
Return an iterator yielding those items of iterable for which function(item) is true.
sum
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
min
With a single iterable argument, return its smallest item.
max
With a single iterable argument, return its biggest item.
all
Return True if bool(x) is True for all values x in the iterable.
any
Return True if bool(x) is True for any x in the iterable.

itertools

Iteration & Functions

Infinite

itertools > Infinite

itertools.count
Return a count object whose .__next__() method returns consecutive values.
itertools.cycle
Return elements from the iterable until it is exhausted.
itertools.repeat
for the specified number of times.

Slice / Filter

itertools > Slice / Filter

itertools.islice
islice(iterable, stop) --> islice object islice(iterable, start, stop[, step]) --> islice object
itertools.takewhile
Return successive entries from an iterable as long as the predicate evaluates to true for each entry.
itertools.dropwhile
Drop items from the iterable while predicate(item) is true.
itertools.filterfalse
Return those items of iterable for which function(item) is false.
itertools.compress
Return data elements corresponding to true selector elements.

Combine

itertools > Combine

itertools.chain
Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then ele…
itertools.chain.from_iterable
Alternative chain() constructor taking a single iterable argument that evaluates lazily.
itertools.zip_longest
Return a zip_longest object whose .__next__() method returns a tuple where the i-th element comes from the i-th iterabl…
itertools.pairwise
Return an iterator of overlapping pairs taken from the input iterator.
itertools.batched
Batch data into tuples of length n.
itertools.tee
Returns a tuple of n independent iterators.

Group / Accumulate

itertools > Group / Accumulate

itertools.groupby
make an iterator that returns consecutive keys and groups from the iterable
itertools.accumulate
Return series of accumulated sums (or other binary function results).
itertools.starmap
Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given se…

Combinatorics

itertools > Combinatorics

itertools.product
Cartesian product of input iterables.
itertools.permutations
Return successive r-length permutations of elements in the iterable.
itertools.combinations
Return successive r-length combinations of elements in the iterable.
itertools.combinations_with_replacement
Return successive r-length combinations of elements in the iterable allowing individual elements to have successive rep…

Functional Tools

Iteration & Functions

functools

Functional Tools > functools

functools.partial
Create a new function with partial application of the given arguments and keywords.
functools.reduce
Apply a function of two arguments cumulatively to the items of an iterable, from left to right.
functools.cache
Simple lightweight unbounded cache.
functools.lru_cache
Least-recently-used cache decorator.
functools.cached_property
Transform a method of a class into a property whose value is computed once and then cached as a normal attribute for th…
functools.wraps
Decorator factory to apply update_wrapper() to a wrapper function
functools.total_ordering
Class decorator that fills in missing ordering methods
functools.singledispatch
Single-dispatch generic function decorator.
functools.cmp_to_key
Convert a cmp= function into a key= function.

operator

Functional Tools > operator

operator.itemgetter
Return a callable object that fetches the given item(s) from its operand.
operator.attrgetter
Return a callable object that fetches the given attribute(s) from its operand.
operator.methodcaller
Return a callable object that calls the given method on its operand.
operator.add
Same as a + b.
operator.mul
Same as a * b.
operator.not_
Same as not a.

Generators & Context Managers

Iteration & Functions

contextlib

Generators & Context Managers > contextlib

contextlib.contextmanager
@contextmanager decorator.
contextlib.asynccontextmanager
@asynccontextmanager decorator.
contextlib.suppress
Context manager to suppress specified exceptions
contextlib.closing
Context to automatically close something at the end of a block.
contextlib.nullcontext
Context manager that does no additional processing.
contextlib.ExitStack
Context manager for dynamic management of a stack of exit callbacks.
contextlib.redirect_stdout
Context manager for temporarily redirecting stdout to another file.
contextlib.chdir
Non thread-safe context manager to change the current working directory.

Generator protocol

Generators & Context Managers > Generator protocol

collections.abc.Iterable
ABC for classes that provide the __iter__() method.
collections.abc.Iterator
ABC for classes that provide the __iter__() and __next__() methods.
collections.abc.Generator
ABC for generator classes that implement the protocol defined in PEP 342 that extends iterators with the send(), throw(…

Objects & Types

Type Inspection

Objects & Types

Types

Type Inspection > Types

type
With one argument, return the type of an object.
isinstance
Return whether an object is an instance of a class or of a subclass thereof.
issubclass
Return whether 'cls' is derived from another class or is the same class.
callable
Return whether the object is callable (i.e., some kind of function).
id
Return the identity of an object.
hash
Return the integer hash value for the given object.

Attributes

Type Inspection > Attributes

getattr
Get a named attribute from an object.
setattr
Sets the named attribute on the given object to the specified value.
hasattr
Return whether the object has an attribute with the given name.
delattr
Deletes the named attribute from the given object.
dir
If called without an argument, return the names in the current scope.
vars
Without arguments, equivalent to locals().

inspect

Type Inspection > inspect

inspect.signature
Get a signature object for the passed callable.
inspect.getsource
Return the text of the source code for an object.
inspect.getmembers
Return all members of an object as (name, value) pairs sorted by name.
inspect.getdoc
Get the documentation string for an object.
inspect.isfunction
Return true if the object is a user-defined function.
inspect.isclass
Return true if the object is a class.

Classes

Objects & Types

Define

Classes > Define

object
The base class of the class hierarchy.
property
Return a property attribute.
classmethod
Convert a function to be a class method.
staticmethod
Convert a function to be a static method.
super
Typical use to call a cooperative superclass method: class C(B): def meth(self, arg): super().meth(arg) This works for …

Abstract

Classes > Abstract

abc.ABC
Helper class that provides a standard way to create an ABC using inheritance.
abc.abstractmethod
A decorator indicating abstract methods.

Enums

Classes > Enums

enum.Enum
Create a collection of name/value pairs.
enum.IntEnum
Enum where members are also (and must be) ints
enum.StrEnum
Enum where members are also (and must be) strings
enum.Flag
Support for flags
enum.auto
Instances are replaced with an appropriate value in Enum class suites.

Copy

Classes > Copy

copy.copy
Shallow copy operation on arbitrary Python objects.
copy.deepcopy
Deep copy operation on arbitrary Python objects.

Type Hints

Objects & Types

typing

Type Hints > typing

typing.Any
Special type indicating an unconstrained type.
typing.Optional
Optional[X] is equivalent to X | None.
typing.Union
Represent a union type
typing.Literal
Special typing form to define literal types (a.k.a.
typing.TypeVar
Type variable.
typing.Generic
Abstract base class for generic types.
typing.Protocol
Base class for protocol classes.
typing.Callable
Deprecated alias to collections.abc.Callable.
typing.cast
Cast a value to a type.
typing.overload
Decorator for overloaded functions/methods.
typing.Self
Used to spell the type of "self" in classes.
typing.TYPE_CHECKING
A special constant that is assumed to be True by static type checkers.

Errors

Exceptions

Errors

Common

Exceptions > Common

Exception
Common base class for all non-exit exceptions.
ValueError
Inappropriate argument value (of correct type).
TypeError
Inappropriate argument type.
KeyError
Mapping key not found.
IndexError
Sequence index out of range.
AttributeError
Attribute not found.
NameError
Name not found globally.
RuntimeError
Unspecified run-time error.
NotImplementedError
Method or function hasn't been implemented yet.
StopIteration
Signal the end from iterator.__next__().
ZeroDivisionError
Second argument to a division or modulo operation was zero.

OS

Exceptions > OS

OSError
Base class for I/O related errors.
FileNotFoundError
File not found.
PermissionError
Not enough permissions.
TimeoutError
Timeout expired.

Groups

Exceptions > Groups

ExceptionGroup
Both of these exception types wrap the exceptions in the sequence excs.
BaseExceptionGroup
A combination of multiple unrelated exceptions.
BaseException.add_note
Add a note to the exception

Tracebacks

Exceptions > Tracebacks

traceback.print_exc
Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'.
traceback.format_exc
Like print_exc() but return a string.

Warnings & Logging

Errors

warnings

Warnings & Logging > warnings

warnings.warn
Issue a warning, or maybe ignore it or raise an exception.
warnings.catch_warnings
A context manager that copies and restores the warnings filter upon exiting the context.
warnings.filterwarnings
Insert an entry into the list of warnings filters (at the front).

logging

Warnings & Logging > logging

logging.getLogger
Return a logger with the specified name, creating it if necessary.
logging.basicConfig
Do basic configuration for the logging system.
logging.debug
Log a message with severity 'DEBUG' on the root logger.
logging.info
Log a message with severity 'INFO' on the root logger.
logging.warning
Log a message with severity 'WARNING' on the root logger.
logging.error
Log a message with severity 'ERROR' on the root logger.
logging.exception
Log a message with severity 'ERROR' on the root logger, with exception information.
logging.Logger
Instances of the Logger class represent a single logging channel.

IO

Console

IO

Print / Read

Console > Print / Read

print
Prints the values to a stream, or to sys.stdout by default.
input
Read a string from standard input.
pprint.pprint
Pretty-print a Python object to a stream [default is sys.stdout].
pprint.pformat
Format a Python object into a pretty-printed representation.

Files & Paths

IO

Open

Files & Paths > Open

open
Open file and return a stream.
io.StringIO
Text I/O implementation using an in-memory buffer.
io.BytesIO
Buffered I/O implementation using an in-memory bytes buffer.

pathlib

Files & Paths > pathlib

pathlib.Path
PurePath subclass that can make system calls.
pathlib.Path.read_text
Open the file in text mode, read it, and close the file.
pathlib.Path.write_text
Open the file in text mode, write to it, and close the file.
pathlib.Path.exists
Whether this path exists.
pathlib.Path.iterdir
Yield path objects of the directory contents.
pathlib.Path.glob
Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative…
pathlib.Path.mkdir
Create a new directory at this given path.
pathlib.Path.unlink
Remove this file or link.
pathlib.PurePath.name
The final path component, if any.
pathlib.PurePath.suffix
The final component's last suffix, if any.
pathlib.PurePath.parent
The logical parent of the path.

os.path

Files & Paths > os.path

os.path.join
Join two or more pathname components, inserting '/' as needed.
os.path.exists
Test whether a path exists.
os.path.isfile
Test whether a path is a regular file
os.path.isdir
Return true if the pathname refers to an existing directory.
os.path.basename
Returns the final component of a pathname
os.path.dirname
Returns the directory component of a pathname
os.path.splitext
Split the extension from a pathname.
os.path.abspath
Return an absolute path.
os.path.expanduser
Expand ~ and ~user constructions.

Copy / Move / Delete

Files & Paths > Copy / Move / Delete

shutil.copy
Copy data and mode bits ("cp src dst").
shutil.copytree
Recursively copy a directory tree and return the destination directory.
shutil.move
Recursively move a file or directory to another location.
shutil.rmtree
Recursively delete a directory tree.
os.remove
Remove a file (same as unlink()).
os.rename
Rename a file or directory.
os.listdir
Return a list containing the names of the files in the directory.
os.walk
Directory tree generator.
os.makedirs
Super-mkdir; create a leaf directory and all intermediate ones.

Temporary

Files & Paths > Temporary

tempfile.TemporaryDirectory
Create and return a temporary directory.
tempfile.NamedTemporaryFile
Create and return a temporary file.
tempfile.mkdtemp
User-callable function to create and return a unique temporary directory.

Data Formats

IO

JSON

Data Formats > JSON

json.dumps
Serialize ``obj`` to a JSON formatted ``str``.
json.loads
Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object.
json.dump
Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object).
json.load
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object.

CSV

Data Formats > CSV

csv.reader
Return a reader object that will process lines from the given iterable.
csv.writer
Return a writer object that will write user data on the given file object.
csv.DictReader
Create an object that operates like a regular reader but maps the information in each row to a dict whose keys are give…
csv.DictWriter
Create an object which operates like a regular writer but maps dictionaries onto output rows.

Other

Data Formats > Other

tomllib.load
Parse TOML from a binary file object.
tomllib.loads
Parse TOML from a string.
pickle.dumps
Return the pickled representation of the object as a bytes object.
pickle.loads
Read and return an object from the given pickle data.
sqlite3.connect
Open a connection to the SQLite database file 'database'.

Environment

Time & Dates

Environment

time

Time & Dates > time

time.time
Return the current time in seconds since the Epoch.
time.sleep
Delay execution for a given number of seconds.
time.perf_counter
Performance counter for benchmarking.
time.monotonic
Monotonic clock, cannot go backward.
time.strftime
Convert a time tuple to a string according to a format specification.

datetime

Time & Dates > datetime

datetime.datetime
A combination of a date and a time.
datetime.datetime.now
Returns new datetime object representing current time local to tz.
datetime.datetime.strptime
Parse string according to the given date and time format (like time.strptime()).
datetime.datetime.strftime
Format using strftime().
datetime.datetime.fromisoformat
Construct a date from a string in ISO 8601 format.
datetime.datetime.isoformat
Return the time formatted according to ISO.
datetime.date
Concrete date type.
datetime.timedelta
Difference between two datetime values.
datetime.timezone
Fixed offset from UTC implementation of tzinfo.
zoneinfo.ZoneInfo
A concrete datetime.tzinfo subclass that represents an IANA time zone specified by the string key.

Concurrency

Environment

asyncio

Concurrency > asyncio

asyncio.run
Execute the coroutine and return the result.
asyncio.gather
Return a future aggregating results from the given coroutines/futures.
asyncio.sleep
Coroutine that completes after a given time (in seconds).
asyncio.create_task
Schedule the execution of a coroutine object in a spawn task.
asyncio.wait_for
Wait for the single Future or coroutine to complete, with timeout.
asyncio.TaskGroup
Asynchronous context manager for managing groups of tasks.
asyncio.timeout
Timeout async context manager.
asyncio.Queue
A queue, useful for coordinating producer and consumer coroutines.

Threads / Processes

Concurrency > Threads / Processes

threading.Thread
A class that represents a thread of control.
threading.Lock
A lock object is a synchronization primitive.
threading.Event
Class implementing event objects.
concurrent.futures.ThreadPoolExecutor
An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.
concurrent.futures.ProcessPoolExecutor
An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes.
concurrent.futures.as_completed
An iterator over the given futures that yields each as it completes.

Subprocess

Concurrency > Subprocess

subprocess.run
Run command with arguments and return a CompletedProcess instance.
subprocess.check_output
Run command with arguments and return its output.
subprocess.Popen
Execute a child program in a new process.
subprocess.CalledProcessError
Raised when run() is called with check=True and the process returns a non-zero exit status.

System

Environment

sys

System > sys

sys.argv
The list of command line arguments passed to a Python script.
sys.exit
Exit the interpreter by raising SystemExit(status).
sys.path
A list of strings that specifies the search path for modules.
sys.version_info
A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial.
sys.platform
A string containing a platform identifier.
sys.stdin
File objects used by the interpreter for standard input, output and errors:
sys.stdout
File objects used by the interpreter for standard input, output and errors:
sys.stderr
File objects used by the interpreter for standard input, output and errors:

os

System > os

os.environ
A mapping object where keys and values are strings that represent the process environment.
os.getenv
Get an environment variable, return None if it doesn't exist.
os.getcwd
Return a unicode string representing the current working directory.
os.chdir
Change the current working directory to the specified path.
os.cpu_count
Return the number of logical CPUs in the system.

Command line

System > Command line

argparse.ArgumentParser
Object for parsing command line strings into Python objects.
argparse.ArgumentParser.add_argument
add_argument(option_string, option_string, ..., name=value, ...)
argparse.ArgumentParser.parse_args
Convert argument strings to objects and assign them as attributes of the namespace.

Misc

System > Misc

shutil.which
Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if ther…
platform.system
Returns the system/OS name, e.g.
platform.python_version
Returns the Python version as string 'major.minor.patchlevel'
importlib.import_module
Import a module.