Python All Built-In Functions
Python All Built-In Functions
Built-in Functions
==================
The Python interpreter has a number of functions and types built into it that
are always available. They are listed here in alphabetical order.
+----------------------------------------------------------------------------------
-----------------+
| Built-in Functions
|
+=========================+=======================+=======================+========
=================+
| | **A** | | **E** | | **L** | |
**R** |
| | :func:`abs` | | :func:`enumerate` | | :func:`len` | | |
func-range|_ |
| | :func:`aiter` | | :func:`eval` | | |func-list|_ |
| :func:`repr` |
| | :func:`all` | | :func:`exec` | | :func:`locals` |
| :func:`reversed` |
| | :func:`any` | | | | |
| :func:`round` |
| | :func:`anext` | | **F** | | **M** | |
|
| | :func:`ascii` | | :func:`filter` | | :func:`map` | |
**S** |
| | | | :func:`float` | | :func:`max` | | |
func-set|_ |
| | **B** | | :func:`format` | | |func-memoryview|_ |
| :func:`setattr` |
| | :func:`bin` | | |func-frozenset|_ | | :func:`min` |
| :func:`slice` |
| | :func:`bool` | | | | |
| :func:`sorted` |
| | :func:`breakpoint` | | **G** | | **N** |
| :func:`staticmethod` |
| | |func-bytearray|_ | | :func:`getattr` | | :func:`next` | | |
func-str|_ |
| | |func-bytes|_ | | :func:`globals` | | |
| :func:`sum` |
| | | | | | **O** |
| :func:`super` |
| | **C** | | **H** | | :func:`object` | |
|
| | :func:`callable` | | :func:`hasattr` | | :func:`oct` | |
**T** |
| | :func:`chr` | | :func:`hash` | | :func:`open` | | |
func-tuple|_ |
| | :func:`classmethod` | | :func:`help` | | :func:`ord` |
| :func:`type` |
| | :func:`compile` | | :func:`hex` | | | |
|
| | :func:`complex` | | | | **P** | |
**V** |
| | | | **I** | | :func:`pow` |
| :func:`vars` |
| | **D** | | :func:`id` | | :func:`print` | |
|
| | :func:`delattr` | | :func:`input` | | :func:`property` | |
**Z** |
| | |func-dict|_ | | :func:`int` | | |
| :func:`zip` |
| | :func:`dir` | | :func:`isinstance` | | | |
|
| | :func:`divmod` | | :func:`issubclass` | | | |
**_** |
| | | | :func:`iter` | | |
| :func:`__import__` |
+-------------------------+-----------------------+-----------------------
+-------------------------+
.. using :func:`dict` would create a link to another page, so local targets are
used, with replacement texts to make the output in the table consistent
.. function:: abs(x)
.. function:: aiter(async_iterable)
.. versionadded:: 3.10
.. function:: all(iterable)
Return ``True`` if all elements of the *iterable* are true (or if the iterable
is empty). Equivalent to::
def all(iterable):
for element in iterable:
if not element:
return False
return True
.. awaitablefunction:: anext(async_iterator)
anext(async_iterator, default)
When awaited, return the next item from the given :term:`asynchronous
iterator`, or *default* if given and the iterator is exhausted.
.. versionadded:: 3.10
.. function:: any(iterable)
def any(iterable):
for element in iterable:
if element:
return True
return False
.. function:: ascii(object)
.. function:: bin(x)
Convert an integer number to a binary string prefixed with "0b". The result
is a valid Python expression. If *x* is not a Python :class:`int` object, it
has to define an :meth:`__index__` method that returns an integer. Some
examples:
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
If the prefix "0b" is desired or not, you can use either of the following ways.
.. class:: bool(x=False)
.. versionchanged:: 3.7
*x* is now a positional-only parameter.
This function drops you into the debugger at the call site. Specifically,
it calls :func:`sys.breakpointhook`, passing ``args`` and ``kws`` straight
through. By default, ``sys.breakpointhook()`` calls
:func:`pdb.set_trace()` expecting no arguments. In this case, it is
purely a convenience function so you don't have to explicitly import
:mod:`pdb` or type as much code to enter the debugger. However,
:func:`sys.breakpointhook` can be set to some other function and
:func:`breakpoint` will automatically call that, allowing you to drop into
the debugger of choice.
If :func:`sys.breakpointhook` is not accessible, this function will
raise :exc:`RuntimeError`.
.. versionadded:: 3.7
.. _func-bytearray:
.. class:: bytearray(source=b'')
bytearray(source, encoding)
bytearray(source, encoding, errors)
:noindex:
The optional *source* parameter can be used to initialize the array in a few
different ways:
.. function:: callable(object)
.. versionadded:: 3.2
This function was first removed in Python 3.0 and then brought back
in Python 3.2.
.. function:: chr(i)
Return the string representing a character whose Unicode code point is the
integer *i*. For example, ``chr(97)`` returns the string ``'a'``, while
``chr(8364)`` returns the string ``'€'``. This is the inverse of :func:`ord`.
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in
base 16). :exc:`ValueError` will be raised if *i* is outside that range.
.. decorator:: classmethod
A class method receives the class as an implicit first argument, just like an
instance method receives the instance. To declare a class method, use this
idiom::
class C:
@classmethod
def f(cls, arg1, arg2): ...
Class methods are different than C++ or Java static methods. If you want those,
see :func:`staticmethod` in this section.
For more information on class methods, see :ref:`types`.
.. versionchanged:: 3.9
Class methods can now wrap other :term:`descriptors <descriptor>` such as
:func:`property`.
.. versionchanged:: 3.10
Class methods now inherit the method attributes (``__module__``,
``__name__``, ``__qualname__``, ``__doc__`` and ``__annotations__``) and
have a new ``__wrapped__`` attribute.
.. versionchanged:: 3.11
Class methods can no longer wrap other :term:`descriptors <descriptor>` such
as
:func:`property`.
Compile the *source* into a code or AST object. Code objects can be executed
by :func:`exec` or :func:`eval`. *source* can either be a normal string, a
byte string, or an AST object. Refer to the :mod:`ast` module documentation
for information on how to work with AST objects.
The *filename* argument should give the file from which the code was read;
pass some recognizable value if it wasn't read from a file (``'<string>'`` is
commonly used).
The *mode* argument specifies what kind of code must be compiled; it can be
``'exec'`` if *source* consists of a sequence of statements, ``'eval'`` if it
consists of a single expression, or ``'single'`` if it consists of a single
interactive statement (in the latter case, expression statements that
evaluate to something other than ``None`` will be printed).
Compiler options and future statements are specified by bits which can be
bitwise ORed together to specify multiple options. The bitfield required to
specify a given future feature can be found as the
:attr:`~__future__._Feature.compiler_flag` attribute on the
:class:`~__future__._Feature` instance in the :mod:`__future__` module.
:ref:`Compiler flags <ast-compiler-flags>` can be found in :mod:`ast`
module, with ``PyCF_`` prefix.
The argument *optimize* specifies the optimization level of the compiler; the
default value of ``-1`` selects the optimization level of the interpreter as
given by :option:`-O` options. Explicit levels are ``0`` (no optimization;
``__debug__`` is true), ``1`` (asserts are removed, ``__debug__`` is false)
or ``2`` (docstrings are removed too).
If you want to parse Python code into its AST representation, see
:func:`ast.parse`.
.. note::
.. warning::
.. versionchanged:: 3.2
Allowed use of Windows and Mac newlines. Also, input in ``'exec'`` mode
does not have to end in a newline anymore. Added the *optimize* parameter.
.. versionchanged:: 3.5
Previously, :exc:`TypeError` was raised when null bytes were encountered
in *source*.
.. versionadded:: 3.8
``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` can now be passed in flags to enable
support for top-level ``await``, ``async for``, and ``async with``.
Return a complex number with the value *real* + *imag*\*1j or convert a string
or number to a complex number. If the first parameter is a string, it will
be interpreted as a complex number and the function must be called without a
second parameter. The second parameter can never be a string. Each argument
may be any numeric type (including complex). If *imag* is omitted, it
defaults to zero and the constructor serves as a numeric conversion like
:class:`int` and :class:`float`. If both arguments are omitted, returns
``0j``.
.. note::
When converting from a string, the string must not contain whitespace
around the central ``+`` or ``-`` operator. For example,
``complex('1+2j')`` is fine, but ``complex('1 + 2j')`` raises
:exc:`ValueError`.
.. versionchanged:: 3.6
Grouping digits with underscores as in code literals is allowed.
.. versionchanged:: 3.8
Falls back to :meth:`__index__` if :meth:`__complex__` and
:meth:`__float__` are not defined.
.. _func-dict:
.. class:: dict(**kwarg)
dict(mapping, **kwarg)
dict(iterable, **kwarg)
:noindex:
.. function:: dir()
dir(object)
Without arguments, return the list of names in the current local scope. With an
argument, attempt to return a list of valid attributes for that object.
If the object has a method named :meth:`__dir__`, this method will be called and
must return the list of attributes. This allows objects that implement a custom
:func:`__getattr__` or :func:`__getattribute__` function to customize the way
:func:`dir` reports their attributes.
If the object does not provide :meth:`__dir__`, the function tries its best to
gather information from the object's :attr:`~object.__dict__` attribute, if
defined, and
from its type object. The resulting list is not necessarily complete and may
be inaccurate when the object has a custom :func:`__getattr__`.
The default :func:`dir` mechanism behaves differently with different types of
objects, as it attempts to produce the most relevant, rather than complete,
information:
* If the object is a module object, the list contains the names of the module's
attributes.
* If the object is a type or class object, the list contains the names of its
attributes, and recursively of the attributes of its bases.
* Otherwise, the list contains the object's attributes' names, the names of its
class's attributes, and recursively of the attributes of its class's base
classes.
.. note::
.. function:: divmod(a, b)
Equivalent to::
.. _func-eval:
The arguments are a string and optional globals and locals. If provided,
*globals* must be a dictionary. If provided, *locals* can be any mapping
object.
>>> x = 1
>>> eval('x+1')
2
This function can also be used to execute arbitrary code objects (such as
those created by :func:`compile`). In this case, pass a code object instead
of a string. If the code object has been compiled with ``'exec'`` as the
*mode* argument, :func:`eval`\'s return value will be ``None``.
If the given source is a string, then leading and trailing spaces and tabs
are stripped.
In all cases, if the optional parts are omitted, the code is executed in the
current scope. If only *globals* is provided, it must be a dictionary
(and not a subclass of dictionary), which
will be used for both the global and the local variables. If *globals* and
*locals* are given, they are used for the global and local variables,
respectively. If provided, *locals* can be any mapping object. Remember
that at the module level, globals and locals are the same dictionary. If exec
gets two separate objects as *globals* and *locals*, the code will be
executed as if it were embedded in a class definition.
If the *globals* dictionary does not contain a value for the key
``__builtins__``, a reference to the dictionary of the built-in module
:mod:`builtins` is inserted under that key. That way you can control what
builtins are available to the executed code by inserting your own
``__builtins__`` dictionary into *globals* before passing it to :func:`exec`.
.. note::
.. note::
The default *locals* act as described for function :func:`locals` below:
modifications to the default *locals* dictionary should not be attempted.
Pass an explicit *locals* dictionary if you need to see effects of the
code on *locals* after function :func:`exec` returns.
.. versionchanged:: 3.11
Added the *closure* parameter.
.. class:: float(x=0.0)
.. index::
single: NaN
single: Infinity
.. productionlist:: float
sign: "+" | "-"
infinity: "Infinity" | "inf"
nan: "nan"
digitpart: `digit` (["_"] `digit`)*
number: [`digitpart`] "." `digitpart` | `digitpart` ["."]
exponent: ("e" | "E") ["+" | "-"] `digitpart`
floatnumber: number [`exponent`]
floatvalue: [`sign`] (`floatnumber` | `infinity` | `nan`)
Examples::
>>> float('+1.23')
1.23
>>> float(' -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
.. versionchanged:: 3.6
Grouping digits with underscores as in code literals is allowed.
.. versionchanged:: 3.7
*x* is now a positional-only parameter.
.. versionchanged:: 3.8
Falls back to :meth:`__index__` if :meth:`__float__` is not defined.
.. index::
single: __format__
single: string; format() (built-in function)
The default *format_spec* is an empty string which usually gives the same
effect as calling :func:`str(value) <str>`.
.. versionchanged:: 3.4
``object().__format__(format_spec)`` raises :exc:`TypeError`
if *format_spec* is not an empty string.
.. _func-frozenset:
.. class:: frozenset(iterable=set())
:noindex:
Return the value of the named attribute of *object*. *name* must be a string.
If the string is the name of one of the object's attributes, the result is the
value of that attribute. For example, ``getattr(x, 'foobar')`` is equivalent to
``x.foobar``. If the named attribute does not exist, *default* is returned if
provided, otherwise :exc:`AttributeError` is raised.
*name* need not be a Python identifier (see :func:`setattr`).
.. note::
.. function:: globals()
Return the dictionary implementing the current module namespace. For code within
functions, this is set when the function is defined and remains the same
regardless of where the function is called.
The arguments are an object and a string. The result is ``True`` if the
string is the name of one of the object's attributes, ``False`` if not. (This
is implemented by calling ``getattr(object, name)`` and seeing whether it
raises an :exc:`AttributeError` or not.)
.. function:: hash(object)
Return the hash value of the object (if it has one). Hash values are
integers. They are used to quickly compare dictionary keys during a
dictionary lookup. Numeric values that compare equal have the same hash
value (even if they are of different types, as is the case for 1 and 1.0).
.. note::
Invoke the built-in help system. (This function is intended for interactive
use.) If no argument is given, the interactive help system starts on the
interpreter console. If the argument is a string, then the string is looked up
as the name of a module, function, class, method, keyword, or documentation
topic, and a help page is printed on the console. If the argument is any other
kind of object, a help page on the object is generated.
.. versionchanged:: 3.4
Changes to :mod:`pydoc` and :mod:`inspect` mean that the reported
signatures for callables are now more comprehensive and consistent.
.. function:: hex(x)
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
.. note::
.. function:: id(object)
.. audit-event:: builtins.id id id
.. function:: input()
input(prompt)
.. class:: int(x=0)
int(x, base=10)
.. versionchanged:: 3.4
If *base* is not an instance of :class:`int` and the *base* object has a
:meth:`base.__index__ <object.__index__>` method, that method is called
to obtain an integer for the base. Previous versions used
:meth:`base.__int__ <object.__int__>` instead of :meth:`base.__index__
<object.__index__>`.
.. versionchanged:: 3.6
Grouping digits with underscores as in code literals is allowed.
.. versionchanged:: 3.7
*x* is now a positional-only parameter.
.. versionchanged:: 3.8
Falls back to :meth:`__index__` if :meth:`__int__` is not defined.
.. versionchanged:: 3.11
The delegation to :meth:`__trunc__` is deprecated.
.. versionchanged:: 3.11
:class:`int` string inputs and string representations can be limited to
help avoid denial of service attacks. A :exc:`ValueError` is raised when
the limit is exceeded while converting a string *x* to an :class:`int` or
when converting an :class:`int` into a string would exceed the limit.
See the :ref:`integer string conversion length limitation
<int_max_str_digits>` documentation.
.. versionchanged:: 3.10
*classinfo* can be a :ref:`types-union`.
.. function:: iter(object)
iter(object, sentinel)
.. function:: len(s)
Return the length (the number of items) of an object. The argument may be a
sequence (such as a string, bytes, tuple, list, or range) or a collection
(such as a dictionary, set, or frozen set).
.. impl-detail::
.. _func-list:
.. class:: list()
list(iterable)
:noindex:
.. function:: locals()
Update and return a dictionary representing the current local symbol table.
Free variables are returned by :func:`locals` when it is called in function
blocks, but not in class blocks. Note that at the module level, :func:`locals`
and :func:`globals` are the same dictionary.
.. note::
The contents of this dictionary should not be modified; changes may not
affect the values of local and free variables used by the interpreter.
There are two optional keyword-only arguments. The *key* argument specifies
a one-argument ordering function like that used for :meth:`list.sort`. The
*default* argument specifies an object to return if the provided iterable is
empty. If the iterable is empty and *default* is not provided, a
:exc:`ValueError` is raised.
If multiple items are maximal, the function returns the first one
encountered. This is consistent with other sort-stability preserving tools
such as ``sorted(iterable, key=keyfunc, reverse=True)[0]`` and
``heapq.nlargest(1, iterable, key=keyfunc)``.
.. versionadded:: 3.4
The *default* keyword-only argument.
.. versionchanged:: 3.8
The *key* can be ``None``.
.. _func-memoryview:
.. class:: memoryview(object)
:noindex:
Return a "memory view" object created from the given argument. See
:ref:`typememoryview` for more information.
There are two optional keyword-only arguments. The *key* argument specifies
a one-argument ordering function like that used for :meth:`list.sort`. The
*default* argument specifies an object to return if the provided iterable is
empty. If the iterable is empty and *default* is not provided, a
:exc:`ValueError` is raised.
If multiple items are minimal, the function returns the first one
encountered. This is consistent with other sort-stability preserving tools
such as ``sorted(iterable, key=keyfunc)[0]`` and ``heapq.nsmallest(1,
iterable, key=keyfunc)``.
.. versionadded:: 3.4
The *default* keyword-only argument.
.. versionchanged:: 3.8
The *key* can be ``None``.
.. function:: next(iterator)
next(iterator, default)
.. class:: object()
.. note::
.. function:: oct(x)
Convert an integer number to an octal string prefixed with "0o". The result
is a valid Python expression. If *x* is not a Python :class:`int` object, it
has to define an :meth:`__index__` method that returns an integer. For
example:
>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'
If you want to convert an integer number to an octal string either with the
prefix
"0o" or not, you can use either of the following ways.
.. index::
single: file object; open() built-in function
*mode* is an optional string that specifies the mode in which the file is
opened. It defaults to ``'r'`` which means open for reading in text mode.
Other common values are ``'w'`` for writing (truncating the file if it
already exists), ``'x'`` for exclusive creation, and ``'a'`` for appending
(which on *some* Unix systems, means that *all* writes append to the end of
the file regardless of the current seek position). In text mode, if
*encoding* is not specified the encoding used is platform-dependent:
:func:`locale.getencoding()` is called to get the current locale encoding.
(For reading and writing raw bytes use binary mode and leave
*encoding* unspecified.) The available modes are:
.. _filemodes:
.. index::
pair: file; modes
========= ===============================================================
Character Meaning
========= ===============================================================
``'r'`` open for reading (default)
``'w'`` open for writing, truncating the file first
``'x'`` open for exclusive creation, failing if the file already exists
``'a'`` open for writing, appending to the end of file if it exists
``'b'`` binary mode
``'t'`` text mode (default)
``'+'`` open for updating (reading and writing)
========= ===============================================================
The default mode is ``'r'`` (open for reading text, a synonym of ``'rt'``).
Modes ``'w+'`` and ``'w+b'`` open and truncate the file. Modes ``'r+'``
and ``'r+b'`` open the file with no truncation.
As mentioned in the :ref:`io-overview`, Python distinguishes between binary
and text I/O. Files opened in binary mode (including ``'b'`` in the *mode*
argument) return contents as :class:`bytes` objects without any decoding. In
text mode (the default, or when ``'t'`` is included in the *mode* argument),
the contents of the file are returned as :class:`str`, the bytes having been
first decoded using a platform-dependent encoding or using the specified
*encoding* if given.
.. note::
* Binary files are buffered in fixed-size chunks; the size of the buffer is
chosen using a heuristic trying to determine the underlying device's "block
size" and falling back on :attr:`io.DEFAULT_BUFFER_SIZE`. On many systems,
the buffer will typically be 4096 or 8192 bytes long.
*encoding* is the name of the encoding used to decode or encode the file.
This should only be used in text mode. The default encoding is platform
dependent (whatever :func:`locale.getencoding` returns), but any
:term:`text encoding` supported by Python can be used.
See the :mod:`codecs` module for the list of supported encodings.
.. index::
single: universal newlines; open() built-in function
.. _open-newline-parameter:
>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
... return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
... print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd) # don't leak a file descriptor
.. index::
single: line-buffered I/O
single: unbuffered I/O
single: buffer size, I/O
single: I/O control; buffering
single: binary mode
single: text mode
module: sys
The ``mode`` and ``flags`` arguments may have been modified or inferred from
the original call.
.. versionchanged:: 3.3
.. versionchanged:: 3.4
.. versionchanged:: 3.5
* If the system call is interrupted and the signal handler does not raise
an
exception, the function now retries the system call instead of raising
an
:exc:`InterruptedError` exception (see :pep:`475` for the rationale).
* The ``'namereplace'`` error handler was added.
.. versionchanged:: 3.6
.. versionchanged:: 3.11
The ``'U'`` mode has been removed.
.. function:: ord(c)
Return *base* to the power *exp*; if *mod* is present, return *base* to the
power *exp*, modulo *mod* (computed more efficiently than
``pow(base, exp) % mod``). The two-argument form ``pow(base, exp)`` is
equivalent to using the power operator: ``base**exp``.
The arguments must have numeric types. With mixed operand types, the
coercion rules for binary arithmetic operators apply. For :class:`int`
operands, the result has the same type as the operands (after coercion)
unless the second argument is negative; in that case, all arguments are
converted to float and a float result is delivered. For example, ``pow(10, 2)``
returns ``100``, but ``pow(10, -2)`` returns ``0.01``. For a negative base of
type :class:`int` or :class:`float` and a non-integral exponent, a complex
result is delivered. For example, ``pow(-9, 0.5)`` returns a value close
to ``3j``.
For :class:`int` operands *base* and *exp*, if *mod* is present, *mod* must
also be of integer type and *mod* must be nonzero. If *mod* is present and
*exp* is negative, *base* must be relatively prime to *mod*. In that case,
``pow(inv_base, -exp, mod)`` is returned, where *inv_base* is an inverse to
*base* modulo *mod*.
.. versionchanged:: 3.8
For :class:`int` operands, the three-argument form of ``pow`` now allows
the second argument to be negative, permitting computation of modular
inverses.
.. versionchanged:: 3.8
Allow keyword arguments. Formerly, only positional arguments were
supported.
Print *objects* to the text stream *file*, separated by *sep* and followed
by *end*. *sep*, *end*, *file*, and *flush*, if present, must be given as
keyword
arguments.
All non-keyword arguments are converted to strings like :func:`str` does and
written to the stream, separated by *sep* and followed by *end*. Both *sep*
and *end* must be strings; they can also be ``None``, which means to use the
default values. If no *objects* are given, :func:`print` will just write
*end*.
.. versionchanged:: 3.3
Added the *flush* keyword argument.
class C:
def __init__(self):
self._x = None
def getx(self):
return self._x
def delx(self):
del self._x
If given, *doc* will be the docstring of the property attribute. Otherwise, the
property will copy *fget*'s docstring (if it exists). This makes it possible to
create read-only properties easily using :func:`property` as
a :term:`decorator`::
class Parrot:
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
This code is exactly equivalent to the first example. Be sure to give the
additional functions the same name as the original property (``x`` in this
case.)
The returned property object also has the attributes ``fget``, ``fset``, and
``fdel`` corresponding to the constructor arguments.
.. versionchanged:: 3.5
The docstrings of property objects are now writeable.
.. _func-range:
.. class:: range(stop)
range(start, stop, step=1)
:noindex:
.. function:: repr(object)
.. function:: reversed(seq)
For the built-in types supporting :func:`round`, values are rounded to the
closest multiple of 10 to the power minus *ndigits*; if two multiples are
equally close, rounding is done toward the even choice (so, for example,
both ``round(0.5)`` and ``round(-0.5)`` are ``0``, and ``round(1.5)`` is
``2``). Any integer value is valid for *ndigits* (positive, zero, or
negative). The return value is an integer if *ndigits* is omitted or
``None``.
Otherwise, the return value has the same type as *number*.
.. note::
.. _func-set:
.. class:: set()
set(iterable)
:noindex:
.. note::
.. class:: slice(stop)
slice(start, stop, step=1)
*reverse* is a boolean value. If set to ``True``, then the list elements are
sorted as if each comparison were reversed.
The sort algorithm uses only ``<`` comparisons between items. While
defining an :meth:`~object.__lt__` method will suffice for sorting,
:PEP:`8` recommends that all six :ref:`rich comparisons
<comparisons>` be implemented. This will help avoid bugs when using
the same data with other ordering tools such as :func:`max` that rely
on a different underlying method. Implementing all six comparisons
also helps avoid confusion for mixed type comparisons which can call
reflected the :meth:`~object.__gt__` method.
For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
.. decorator:: staticmethod
A static method does not receive an implicit first argument. To declare a static
method, use this idiom::
class C:
@staticmethod
def f(arg1, arg2, ...): ...
Static methods in Python are similar to those found in Java or C++. Also, see
:func:`classmethod` for a variant that is useful for creating alternate class
constructors.
def regular_function():
...
class C:
method = staticmethod(regular_function)
.. versionchanged:: 3.10
Static methods now inherit the method attributes (``__module__``,
``__name__``, ``__qualname__``, ``__doc__`` and ``__annotations__``),
have a new ``__wrapped__`` attribute, and are now callable as regular
functions.
.. index::
single: string; str() (built-in function)
.. _func-str:
.. class:: str(object='')
str(object=b'', encoding='utf-8', errors='strict')
:noindex:
Sums *start* and the items of an *iterable* from left to right and returns the
total. The *iterable*'s items are normally numbers, and the start value is not
allowed to be a string.
.. versionchanged:: 3.8
The *start* parameter can be specified as a keyword argument.
.. class:: super()
super(type, object_or_type=None)
There are two typical use cases for *super*. In a class hierarchy with
single inheritance, *super* can be used to refer to parent classes without
naming them explicitly, thus making the code more maintainable. This use
closely parallels the use of *super* in other programming languages.
class C(B):
def method(self, arg):
super().method(arg) # This does the same thing as:
# super(C, self).method(arg)
Also note that, aside from the zero argument form, :func:`super` is not
limited to use inside methods. The two argument form specifies the
arguments exactly and makes the appropriate references. The zero
argument form only works inside a class definition, as the compiler fills
in the necessary details to correctly retrieve the class being defined,
as well as accessing the current instance for ordinary methods.
.. _func-tuple:
.. class:: tuple()
tuple(iterable)
:noindex:
.. class:: type(object)
type(name, bases, dict, **kwds)
With one argument, return the type of an *object*. The return value is a
type object and generally the same object as returned by
:attr:`object.__class__ <instance.__class__>`.
>>> class X:
... a = 1
...
>>> X = type('X', (), dict(a=1))
Keyword arguments provided to the three argument form are passed to the
appropriate metaclass machinery (usually :meth:`~object.__init_subclass__`)
in the same way that keywords in a class
definition (besides *metaclass*) would.
.. versionchanged:: 3.6
Subclasses of :class:`type` which don't override ``type.__new__`` may no
longer use the one-argument form to get the type of an object.
.. function:: vars()
vars(object)
Example::
One thing to consider is that the iterables passed to :func:`zip` could have
different lengths; sometimes by design, and sometimes because of a bug in
the code that prepared these iterables. Python offers three different
approaches to dealing with this issue:
..
This doctest is disabled because doctest does not support capturing
output and exceptions in the same code unit.
https://github.com/python/cpython/issues/65382
* Shorter iterables can be padded with a constant value to make all the
iterables have the same length. This is done by
:func:`itertools.zip_longest`.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> list(zip(x, y))
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
.. versionchanged:: 3.10
Added the ``strict`` argument.
.. index::
statement: import
module: imp
.. note::
The function imports the module *name*, potentially using the given *globals*
and *locals* to determine how to interpret the name in a package context.
The *fromlist* gives the names of objects or submodules that should be
imported from the module given by *name*. The standard implementation does
not use its *locals* argument at all and uses its *globals* only to
determine the package context of the :keyword:`import` statement.
Note how :func:`__import__` returns the toplevel module here because this is
the object that is bound to a name by the :keyword:`import` statement.
On the other hand, the statement ``from spam.ham import eggs, sausage as
saus`` results in ::
.. versionchanged:: 3.3
Negative values for *level* are no longer supported (which also changes
the default value to 0).
.. versionchanged:: 3.9
When the command line options :option:`-E` or :option:`-I` are being used,
the environment variable :envvar:`PYTHONCASEOK` is now ignored.
.. rubric:: Footnotes
.. [#] Note that the parser only accepts the Unix-style end of line convention.
If you are reading the code from a file, make sure to use newline conversion
mode to convert Windows or Mac-style newlines.