:mod:`builtins` -- builtin functions, constants, exceptions, and decorators =========================================================================== .. module:: builtins :synopsis: builtin functions, constants, exceptions, and decorators All builtin functions, constants, exceptions, and decorators are described here. They are also available by importing from the ``builtins`` module. As a convenience this documentation will provide links to the Python 3.5 documentation to expand on topics, but as MicroPython is a subset of Python 3.5 not everything in the referenced documentation will apply. List of functions ################# :func:`abs` :func:`all` :func:`any` :func:`ascii` :func:`bin` :func:`bool` :func:`bytearray` :func:`bytes` :func:`callable` :func:`chr` :func:`classmethod` :func:`compile` :func:`complex` :func:`delattr` :func:`dict` :func:`dir` :func:`divmod` :func:`enumerate` :func:`eval` :func:`exec` :func:`filter` :func:`float` :func:`format` :func:`frozenset` :func:`getattr` :func:`globals` :func:`hasattr` :func:`hash` :func:`help` :func:`hex` :func:`id` :func:`input` :func:`int` :func:`isinstance` :func:`issubclass` :func:`iter` :func:`len` :func:`list` :func:`locals` :func:`map` :func:`max` :func:`memoryview` :func:`min` :func:`next` :func:`object` :func:`oct` :func:`open` :func:`ord` :func:`pow` :func:`print` :func:`property` :func:`range` :func:`repr` :func:`reversed` :func:`round` :func:`set` :func:`setattr` :func:`slice` :func:`sorted` :func:`staticmethod` :func:`str` :func:`sum` :func:`super` :func:`tuple` :func:`type` :func:`zip` :func:`__import__` List of constants, exceptions, and decorators ############################################# :exc:`ArithmeticError` :exc:`AssertionError` :exc:`AttributeError` :exc:`BaseException` :exc:`EOFError` :data:`Ellipsis` :exc:`Exception` :data:`False` :exc:`GeneratorExit` :exc:`ImportError` :exc:`IndentationError` :exc:`IndexError` :exc:`KeyboardInterrupt` :exc:`LogAccessError` :exc:`LookupError` :func:`MEASUREMENT` :exc:`MemoryError` :exc:`NameError` :data:`None` :exc:`NotImplementedError` :exc:`OSError` :exc:`OverflowError` :exc:`RuntimeError` :exc:`StopAsyncIteration` :exc:`StopIteration` :exc:`SyntaxError` :exc:`SystemAbort` :exc:`SystemExit` :func:`TASK` :func:`TXFORMAT` :exc:`TimeoutError` :data:`True` :exc:`TypeError` :exc:`UnicodeError` :exc:`ValueError` :exc:`ViperTypeError` :exc:`ZeroDivisionError` Functions ######### .. function:: abs(x) :module: Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned. .. function:: all(iterable) :module: 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 .. function:: any(iterable) :module: Return ``True`` if any element of the *iterable* is true. If the iterable is empty, return ``False``. Equivalent to:: def any(iterable): for element in iterable: if element: return True return False .. function:: bin(x) :module: Convert an integer number to a binary string prefixed with "0b" examples: >>> bin(3) '0b11' >>> bin(-10) '-0b1010' If the "0b" prefix is not desired or you need leading zeros, you can use either of the following ways. >>> '{:b}'.format(14) '1110' >>> '{:08b}'.format(14) '00001110' .. function:: bool([x]) :module: .. index:: pair: Boolean; type Return a Boolean value, i.e. one of ``True`` or ``False``. *x* is converted using the standard :ref:`truth testing procedure `. If *x* is false or omitted, this returns ``False``; otherwise it returns ``True``. The :class:`py:bool` class is a subclass of :class:`int` (see :ref:`typesnumeric`). It cannot be subclassed further. Its only instances are ``False`` and ``True`` .. function:: bytearray([source]) :module: Return a new array of bytes. The :class:`py:bytearray` class is a mutable sequence of integers in the range 0 <= x < 256. , described in :ref:`typesseq-mutable`, as well as most methods that the :class:`bytes` type has, see :ref:`bytes-methods`. The optional *source* parameter can be used to initialize the array in a few different ways: * If it is a *string*, it will be automatically converted to bytes. * If it is an *integer*, the array will have that size and will be initialized with null bytes. * If it is an object conforming to the *buffer* interface, a read-only buffer of the object will be used to initialize the bytes array. * If it is an *iterable*, it must be an iterable of integers in the range ``0 <= x < 256``, which are used as the initial contents of the array. Without an argument, an array of size 0 is created. See also :ref:`binaryseq` and :ref:`typebytearray`. .. function:: bytes([source]) :module: Return a new :class:`py:bytes` object, which is an immutable sequence of integers in the range ``0 <= x < 256``. :class:`py:bytes` is an immutable version of :class:`bytearray` -- it has the same non-mutating methods and the same indexing and slicing behavior. Accordingly, constructor arguments are interpreted as for :func:`bytearray` except a *string* literal is not allowed (use a *bytes* literal instead). See also :ref:`binaryseq`, :ref:`typebytes`, and :ref:`bytes-methods`. .. function:: callable(object) :module: Return :const:`True` if the *object* argument appears callable, :const:`False` if not. If this returns true, it is still possible that a call fails, but if it is false, calling *object* will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a :meth:`__call__` method. .. function:: chr(i) :module: 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. .. function:: classmethod(function) :module: Return a class method for *function*. A class method receives the class as 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, ...): ... The ``@classmethod`` form is a function :term:`decorator` -- see the description of function definitions in :ref:`function` for details. It can be called either on the class (such as ``C.f()``) or on an instance (such as ``C().f()``). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. 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, consult the documentation on the standard type hierarchy in :ref:`types`. .. function:: compile(source, filename, mode) :module: Compile the *source* into a code object. Code objects can be executed by :func:`exec` or :func:`eval`. *source* can either be a normal string, or a byte string. 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 (``''`` 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). This function raises :exc:`SyntaxError` if the compiled source is invalid, and :exc:`ValueError` if the source contains null bytes. .. note:: When compiling a string with multi-line code in ``'single'`` or ``'eval'`` mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the :mod:`code` module. .. function:: complex([real[, imag]]) :module: Return a complex number with the value *real* + *imag*\*1j. 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``. The complex type is described in :ref:`typesnumeric`. .. function:: dict(**kwarg) dict(mapping, **kwarg) dict(iterable, **kwarg) :module: Create a new :class:`py:dict` object initialized from an optional positional argument and a possibly empty set of keyword arguments. If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an :term:`iterable` object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary. If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument. To illustrate, the following examples all return a dictionary equal to ``{"one": 1, "two": 2, "three": 3}``:: >>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> a == b == c == d == e True Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used. .. function:: dir([object]) :module: 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. 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. .. function:: divmod(a, b) :module: Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as ``(a // b, a % b)``. For floating point numbers the result is ``(q, a % b)``, where *q* is usually ``math.floor(a / b)`` but may be 1 less than that. In any case ``q * b + a % b`` is very close to *a*, if ``a % b`` is non-zero it has the same sign as *b*, and ``0 <= abs(a % b) < abs(b)``. .. function:: enumerate(iterable, start=0) :module: Return an enumerate object. *iterable* must be a sequence, an :term:`iterator`, or some other object which supports iteration. The :meth:`~iterator.__next__` method of the iterator returned by :func:`enumerate` returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*. >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] Equivalent to:: def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 .. function:: eval(expression, globals=None, locals=None) :module: 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. The *expression* argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the *globals* and *locals* dictionaries as global and local namespace. If the *globals* dictionary is present and lacks '__builtins__', the current globals are copied into *globals* before *expression* is parsed. This means that *expression* normally has full access to the standard :mod:`builtins` module and restricted environments are propagated. If the *locals* dictionary is omitted it defaults to the *globals* dictionary. If both dictionaries are omitted, the expression is executed in the environment where :func:`eval` is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example: >>> 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``. Hints: dynamic execution of statements is supported by the :func:`exec` function. The :func:`globals` and :func:`locals` functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by :func:`eval` or :func:`exec`. .. function:: exec(object[, globals[, locals]]) :module: .. index:: builtin: exec This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [#]_ If it is a code object, it is simply executed. In all cases, the code that's executed is expected to be valid as file input (see the section "File input" in the Reference Manual). Be aware that the :keyword:`return` and :keyword:`yield` statements may not be used outside of function definitions even within the context of code passed to the :func:`exec` function. The return value is ``None``. 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, 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 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:: The built-in functions :func:`globals` and :func:`locals` return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to :func:`exec`. .. 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. .. function:: filter(function, iterable) :module: Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is ``None``, the identity function is assumed, that is, all elements of *iterable* that are false are removed. Note that ``filter(function, iterable)`` is equivalent to the generator expression ``(item for item in iterable if function(item))`` if function is not ``None`` and ``(item for item in iterable if item)`` if function is ``None``. .. function:: float([x]) :module: .. index:: single: NaN single: Infinity single: string; format() (built-in function) Return a floating point number constructed from a number or string *x*. If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be ``'+'`` or ``'-'``; a ``'+'`` sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed: .. productionlist:: sign: "+" | "-" infinity: "Infinity" | "inf" nan: "nan" numeric_value: `floatnumber` | `infinity` | `nan` numeric_string: [`sign`] `numeric_value` Here ``floatnumber`` is the form of a Python floating-point literal, described in :ref:`floating`. Case is not significant, so, for example, "inf", "Inf", "INFINITY" and "iNfINity" are all acceptable spellings for positive infinity. Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python's floating point precision) is returned. If the argument is outside the range of a Python float, an :exc:`OverflowError` will be raised. If no argument is given, ``0.0`` is returned. Examples:: >>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf The float type is described in :ref:`typesnumeric`. .. function:: frozenset([iterable]) :module: Returns a new :class:`py:frozenset` object, optionally with elements taken from *iterable*. :class:`py:frozenset` is a built-in class. See :class:`py:frozenset` and :ref:`types-set` for documentation about this class. A :class:`py:frozenset` is an immutable version of a regular :class:`set`. This means it cannot be modified. As it is immutable, a hash value for a frozenset can be computed and it may be used as key in a dictionary. For other containers see the built-in :class:`set`, :class:`list`, :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections` module. .. function:: getattr(object, name[, default]) :module: 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. .. function:: globals() :module: Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called). .. function:: hasattr(object, name) :module: 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) :module: 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:: For objects with custom :meth:`__hash__` methods, note that :func:`hash` truncates the return value based on the bit width of the host machine. See :meth:`__hash__` for details. .. function:: help([object]) :module: Invoke the built-in help system which is very limited but can help to display some information about keywords, modules, functions, and methods. .. function:: hex(x) :module: Convert an integer number to a lowercase hexadecimal string prefixed with "0x", for example: >>> hex(255) '0xff' >>> hex(-42) '-0x2a' See also :func:`int` for converting a hexadecimal string to an integer. .. function:: id(object) :module: Return the "identity" of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same :func:`id` value. This is the address of the object in memory. .. function:: input([prompt]) :module: If the *prompt* argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, :exc:`EOFError` is raised. Example:: >>> s = input('--> ') # doctest: +SKIP --> Monty Python's Flying Circus >>> s # doctest: +SKIP "Monty Python's Flying Circus" .. function:: int(x=0) :module: Return an integer object constructed from a number, string *x*, or return ``0`` if no arguments are given. For floating point numbers, this truncates towards zero. If *x* is not a number, then *x* must be a string, :class:`bytes`, or :class:`bytearray` instance representing an :ref:`integer literal `. Optionally, the literal can be preceded by ``+`` or ``-`` (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with ``a`` to ``z`` (or ``A`` to ``Z``) having values 10 to 35. The allowed values are 0 and 2--36. Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``, ``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that ``int('010', 0)`` is not legal, while ``int('010')`` is, as well as ``int('010', 8)``. The integer type is described in :ref:`typesnumeric`. .. function:: isinstance(object, classinfo) :module: Return true if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect or :term:`virtual `) subclass thereof. If *object* is not an object of the given type, the function always returns false. If *classinfo* is a tuple of type objects (or recursively, other such tuples), return true if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a :exc:`TypeError` exception is raised. .. function:: issubclass(class, classinfo) :module: Return true if *class* is a subclass (direct, indirect or :term:`virtual `) of *classinfo*. A class is considered a subclass of itself. *classinfo* may be a tuple of class objects, in which case every entry in *classinfo* will be checked. In any other case, a :exc:`TypeError` exception is raised. .. function:: iter(object) :module: Get an :term:`iterator` from an object. *object* must be a collection object which supports the iteration protocol (the :meth:`__iter__` method), or it must support the sequence protocol (the :meth:`__getitem__` method with integer arguments starting at ``0``). If it does not support either of those protocols, :exc:`TypeError` is raised. See also :ref:`typeiter`. .. function:: len(object) :module: 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). .. function:: list([iterable]) :module: Returns a new :class:`py:list` initialized from iterable's items. Lists may be constructed in several ways: * Using a pair of square brackets to denote the empty list: ``[]`` * Using square brackets, separating items with commas: ``[a]``, ``[a, b, c]`` * Using a list comprehension: ``[x for x in iterable]`` * Using the type constructor: ``list()`` or ``list(iterable)`` The constructor builds a list whose items are the same and in the same order as *iterable*'s items. *iterable* may be either a sequence, a container that supports iteration, or an iterator object. If *iterable* is already a list, a copy is made and returned, similar to ``iterable[:]``. For example, ``list('abc')`` returns ``['a', 'b', 'c']`` and ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. If no argument is given, the constructor creates a new empty list, ``[]``. Many other operations also produce lists, including the :func:`sorted` built-in. Lists implement all of the common and mutable sequence operations. Lists also provide the following additional method: .. method:: list.sort(*, key=None, reverse=None) This method sorts the list in place, using only ``<`` comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state). :meth:`sort` accepts two arguments that can only be passed by keyword keyword-only arguments: *key* specifies a function of one argument that is used to extract a comparison key from each list element (for example, ``key=str.lower``). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of ``None`` means that list items are sorted directly without calculating a separate key value. *reverse* is a boolean value. If set to ``True``, then the list elements are sorted as if each comparison were reversed. This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use :func:`sorted` to explicitly request a new sorted list instance). The :meth:`sort` method is *not* guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal --- this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). .. note:: Standard Python does guarantee that sorts will be stable, so, you may not see the same results when simulating a program. .. function:: locals() :module: 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:: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter. .. function:: map(function, iterable, ...) :module: Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterable* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. .. function:: max(iterable) max(arg1, arg2, *args) :module: Return the largest item in an iterable or the largest of two or more arguments. If one positional argument is provided, it should be an :term:`iterable`. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. 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]``. .. function:: memoryview(obj) :module: Return a new :class:`py:memoryview` object that permits access to the internal data of *obj* without copying. Accessing the memoryview of an object may be more efficient than accessing the object directly because copying does not occur. *obj* must support the buffer protocol. Built-in objects that support the buffer protocol include :class:`bytes` and :class:`bytearray`. A :class:`memoryview` has the notion of an *element*, which is the atomic memory unit handled by the originating object *obj*. For many simple types such as :class:`bytes` and :class:`bytearray`, an element is a single byte, but other types such as :class:`array.array` may have bigger elements. ``len(view)`` will return the number of elements in the view. A :class:`memoryview` supports slicing and indexing to expose its data. One-dimensional slicing will result in a subview:: >>> v = memoryview(b'abcefg') >>> v[1] 98 >>> v[-1] 103 >>> v[1:4] >>> bytes(v[1:4]) b'bce' .. function:: min(iterable) min(arg1, arg2, *args) :module: Return the smallest item in an iterable or the smallest of two or more arguments. If one positional argument is provided, it should be an :term:`iterable`. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned. 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]``. .. function:: next(iterator) :module: Retrieve the next item from the *iterator* by calling its :meth:`~iterator.__next__` method. If the iterator is exhausted, otherwise :exc:`StopIteration` is raised. .. function:: object() :module: Return a new featureless object. :class:`py:object` is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments. .. note:: :class:`py:object` does *not* have a :attr:`~object.__dict__`, so you can't assign arbitrary attributes to an instance of the :class:`py:object` class. .. function:: oct(x) :module: .. index:: single: file object; open() built-in function Convert an integer number to an octal string prefixed with "0o". .. function:: open(file, mode='r', encoding=None) :module: Open *file* and return a corresponding :term:`file object`. If the file cannot be opened, an :exc:`OSError` is raised. *file* is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened. *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. *encoding* is currently ignored. The available modes are: ========= =============================================================== 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 the file if it exists ``'b'`` binary mode ``'t'`` text mode (default) ``'+'`` open a disk file for updating (reading and writing) ========= =============================================================== The default mode is ``'r'`` (open for reading text, synonym of ``'rt'``). For binary read-write access, the mode ``'w+b'`` opens and truncates the file to 0 bytes. ``'r+b'`` opens the file without 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. * Binary files are buffered in fixed-size chunks. * "Interactive" text files use line buffering. Other text files use the policy described above for binary files. The type of :term:`file object` returned by the :func:`open` function depends on the mode. When :func:`open` is used to open a file in a text mode (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of :class:`io.TextIOBase` (specifically :class:`io.TextIOWrapper`). When used to open a file in a binary mode with buffering, the returned class is a subclass of :class:`io.BufferedIOBase`. The exact class varies: in read binary mode, it returns an :class:`io.BufferedReader`; in write binary and append binary modes, it returns an :class:`io.BufferedWriter`, and in read/write mode, it returns an :class:`io.BufferedRandom`. When buffering is disabled, the raw stream, a subclass of :class:`io.RawIOBase`, :class:`io.FileIO`, is returned. .. 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 See also the file handling modules, such as, :mod:`os`. .. function:: ord(c) :module: Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ``ord('a')`` returns the integer ``97`` and ``ord('€')`` (Euro sign) returns ``8364``. This is the inverse of :func:`chr`. .. function:: pow(x, y[, z]) :module: Return *x* to the power *y*; if *z* is present, return *x* to the power *y*, modulo *z* (computed more efficiently than ``pow(x, y) % z``). The two-argument form ``pow(x, y)`` is equivalent to using the power operator: ``x**y``. 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, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. If the second argument is negative, the third argument must be omitted. If *z* is present, *x* and *y* must be of integer types, and *y* must be non-negative. .. function:: print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False) :module: 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*. The *file* argument must be an object with a ``write(string)`` method; if it is not present or ``None``, :data:`sys.stdout` will be used. Since printed arguments are converted to text strings, :func:`print` cannot be used with binary mode file objects. For these, use ``file.write(...)`` instead. Whether output is buffered is usually determined by *file*, but if the *flush* keyword argument is true, the stream is forcibly flushed. .. function:: property(fget=None, fset=None, fdel=None, doc=None) :module: Return a property attribute. *fget* is a function for getting an attribute value. *fset* is a function for setting an attribute value. *fdel* is a function for deleting an attribute value. And *doc* creates a docstring for the attribute. A typical use is to define a managed attribute ``x``:: class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") If *c* is an instance of *C*, ``c.x`` will invoke the getter, ``c.x = value`` will invoke the setter and ``del c.x`` the deleter. 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 The ``@property`` decorator turns the :meth:`voltage` method into a "getter" for a read-only attribute with the same name, and it sets the docstring for *voltage* to "Get the current voltage." A property object has :attr:`~property.getter`, :attr:`~property.setter`, and :attr:`~property.deleter` methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:: 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. .. function:: range(stop) range(start, stop[, step]) :module: Returns a :class:`py:range` object containing an immutable sequence type, as documented in :ref:`typesseq-range` and :ref:`typesseq`. The arguments to the range function must be an integer If the *step* argument is omitted, it defaults to ``1``. If the *start* argument is omitted, it defaults to ``0``. If *step* is zero, :exc:`ValueError` is raised. For a positive *step*, the contents of a range ``r`` are determined by the formula ``r[i] = start + step*i`` where ``i >= 0`` and ``r[i] < stop``. For a negative *step*, the contents of the range are still determined by the formula ``r[i] = start + step*i``, but the constraints are ``i >= 0`` and ``r[i] > stop``. A range object will be empty if ``r[0]`` does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices. Ranges containing absolute values larger than :data:`sys.maxsize` are permitted but some features (such as :func:`len`) may raise :exc:`OverflowError`. Range examples:: >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> list(range(0, 30, 5)) [0, 5, 10, 15, 20, 25] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(0, -10, -1)) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> list(range(0)) [] >>> list(range(1, 0)) [] Ranges implement all of the :ref:`common ` sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern). .. function:: repr(object) :module: Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to :func:`eval`, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a :meth:`__repr__` method. .. function:: reversed(seq) :module: Return a reverse :term:`iterator`. *seq* must be an object which has a :meth:`__reversed__` method or supports the sequence protocol (the :meth:`__len__` method and the :meth:`__getitem__` method with integer arguments starting at ``0``). .. function:: round(number[, ndigits]) :module: Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is ``None``, it returns the nearest integer to its input. 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 called with one argument, otherwise of the same type as *number*. .. function:: set([iterable]) :module: Return a new :class:`py:set` object, optionally with elements taken from *iterable*. ``set`` is a built-in class. See :class:`py:set` and :ref:`types-set` for documentation about this class. For other containers see the built-in :class:`frozenset`, :class:`list`, :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections` module. .. function:: setattr(object, name, value) :module: This is the counterpart of :func:`getattr`. The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, ``setattr(x, 'foobar', 123)`` is equivalent to ``x.foobar = 123``. .. function:: slice(stop) slice(start, stop[, step]) :module: .. index:: single: Numerical Python Return a :term:`slice` object representing the set of indices specified by ``range(start, stop, step)``. The *start* and *step* arguments default to ``None``. Slice objects have read-only data attributes :attr:`~slice.start`, :attr:`~slice.stop` and :attr:`~slice.step` which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: ``a[start:stop:step]`` or ``a[start:stop, i]``. .. function:: sorted(iterable[, key][, reverse]) :module: Return a new sorted list from the items in *iterable*. Has two optional arguments which must be specified as keyword arguments. *key* specifies a function of one argument that is used to extract a comparison key from each list element: ``key=str.lower``. The default value is ``None`` (compare the elements directly). *reverse* is a boolean value. If set to ``True``, then the list elements are sorted as if each comparison were reversed. Use :func:`functools.cmp_to_key` to convert an old-style *cmp* function to a *key* function. The built-in :func:`sorted` function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal --- this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`. .. function:: staticmethod(function) :module: Return a static method for *function*. 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, ...): ... The ``@staticmethod`` form is a function :term:`decorator` -- see the description of function definitions in :ref:`function` for details. It can be called either on the class (such as ``C.f()``) or on an instance (such as ``C().f()``). The instance is ignored except for its class. 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. For more information on static methods, consult the documentation on the standard type hierarchy in :ref:`types`. .. function:: str(object='') str(object=b'', encoding='utf-8', errors='strict') :module: .. index:: single: string; str() (built-in function) Create a new :class:`py:str` object from the given *object*. If *object* is not provided, returns the empty string. Otherwise, the behavior of ``str()`` depends on whether *encoding* or *errors* is given, as follows. If neither *encoding* nor *errors* is given, ``str(object)`` returns :meth:`object.__str__() `, which is the "informal" or nicely printable string representation of *object*. For string objects, this is the string itself. If *object* does not have a :meth:`~object.__str__` method, then :func:`str` falls back to returning :meth:`repr(object) `. If at least one of *encoding* or *errors* is given, *object* should be a :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object, then ``str(bytes, encoding, errors)`` is equivalent to :meth:`bytes.decode(encoding, errors) `. Otherwise, the bytes object underlying the buffer object is obtained before calling :meth:`bytes.decode`. See :ref:`binaryseq` and :ref:`bufferobjects` for information on buffer objects. Passing a :class:`bytes` object to :func:`str` without the *encoding* or *errors* arguments falls under the first case of returning the informal string representation. For example:: >>> str(b'Zoot!') "b'Zoot!'" For more information on the ``str`` class and its methods, see :ref:`textseq` and the :ref:`string-methods` section below. To output formatted strings, see the :ref:`formatstrings` section. In addition, see the :ref:`stringservices` section. .. note:: Keyword arguments are not supported, *encoding* always defaults to "utf-8" regardless of what is passed, and *errors* are ignored. .. function:: sum(iterable[, start]) :module: Sums *start* and the items of an *iterable* from left to right and returns the total. *start* defaults to ``0``. The *iterable*'s items are normally numbers, and the start value is not allowed to be a string. For some use cases, there are good alternatives to :func:`sum`. The preferred, fast way to concatenate a sequence of strings is by calling ``''.join(sequence)``. .. function:: super([type[, object-or-type]]) :module: Return a proxy object that delegates method calls to a parent or sibling class of *type*. This is useful for accessing inherited methods that have been overridden in a class. If the second argument is omitted, the super object returned is unbound. If the second argument is an object, ``isinstance(obj, type)`` must be true. If the second argument is a type, ``issubclass(type2, type)`` must be true (this is useful for classmethods). 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. .. note:: super() in MicroPython does not currently support multiple inheritence Here's an example of accessing a base-class's method from a sub-class using super():: class BaseClass: def method(self): print("in BaseClass's method()") class SubClass(BaseClass): def method(self): print("in SubClass's method()") return super().method() # This does the same thing as: # super(SubClass, self).method() >>> a = SubClass() >>> a.method() in SubClass's method in BaseClass's method For practical suggestions on how to design cooperative classes using :func:`super`, see `guide to using super() `_. .. function:: tuple([iterable]) :module: Returns a :class:`py:tuple` object containing an immutable sequence. Tuples may be constructed in a number of ways: * Using a pair of parentheses to denote the empty tuple: ``()`` * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)`` * Separating items with commas: ``a, b, c`` or ``(a, b, c)`` * Using the :func:`tuple` built-in: ``tuple()`` or ``tuple(iterable)`` The constructor builds a tuple whose items are the same and in the same order as *iterable*'s items. *iterable* may be either a sequence, a container that supports iteration, or an iterator object. If *iterable* is already a tuple, it is returned unchanged. For example, ``tuple('abc')`` returns ``('a', 'b', 'c')`` and ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``. If no argument is given, the constructor creates a new empty tuple, ``()``. Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, ``f(a, b, c)`` is a function call with three arguments, while ``f((a, b, c))`` is a function call with a 3-tuple as the sole argument. Tuples implement all of the :ref:`common ` sequence operations. .. function:: type(object) type(name, bases, dict) :module: .. index:: object: type 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__ `. The :func:`isinstance` built-in function is recommended for testing the type of an object, because it takes subclasses into account. With three arguments, return a new type object. This is essentially a dynamic form of the :keyword:`class` statement. The *name* string is the class name and becomes the :attr:`~definition.__name__` attribute; the *bases* tuple itemizes the base classes and becomes the :attr:`~class.__bases__` attribute; and the *dict* dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the :attr:`~object.__dict__` attribute. For example, the following two statements create identical :class:`py:type` objects: >>> class X: ... a = 1 ... >>> X = type('X', (object,), dict(a=1)) .. function:: zip(*iterables) :module: Make an iterator that aggregates elements from each of the iterables. Returns an iterator of tuples, where the *i*-th tuple contains the *i*-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:: def zip(*iterables): # zip('ABCD', 'xy') --> Ax By sentinel = object() iterators = [iter(it) for it in iterables] while iterators: result = [] for it in iterators: elem = next(it, sentinel) if elem is sentinel: return result.append(elem) yield tuple(result) The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using ``zip(*[iter(s)]*n)``. This repeats the *same* iterator ``n`` times so that each output tuple has the result of ``n`` calls to the iterator. This has the effect of dividing the input into n-length chunks. :func:`zip` should only be used with unequal length inputs when you don't care about trailing, unmatched values from the longer iterables. :func:`zip` in conjunction with the ``*`` operator can be used to unzip a list:: >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> list(zipped) [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zip(x, y)) >>> x == list(x2) and y == list(y2) True .. function:: __import__(name, globals=None, locals=None, fromlist=(), level=0) :module: .. index:: statement: import module: imp This function is invoked by the :keyword:`import` statement. It can be replaced (by importing the :mod:`builtins` module and assigning to ``builtins.__import__``) in order to change semantics of the :keyword:`import` statement. 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. *level* specifies whether to use absolute or relative imports. ``0`` (the default) means only perform absolute imports. Positive values for *level* indicate the number of parent directories to search relative to the directory of the module calling :func:`__import__` (see :pep:`328` for the details). When the *name* variable is of the form ``package.module``, normally, the top-level package (the name up till the first dot) is returned, *not* the module named by *name*. However, when a non-empty *fromlist* argument is given, the module named by *name* is returned. For example, the statement ``import spam`` results in bytecode resembling the following code:: spam = __import__('spam', globals(), locals(), [], 0) The statement ``import spam.ham`` results in this call:: spam = __import__('spam.ham', globals(), locals(), [], 0) 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 :: _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage Here, the ``spam.ham`` module is returned from :func:`__import__`. From this object, the names to import are retrieved and assigned to their respective names. Constants, exceptions, and decorators ##################################### A number of constants and exceptions live in the built-in namespace. They are: .. exception:: ArithmeticError :module: The base class for those built-in exceptions that are raised for various arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`, :exc:`FloatingPointError` .. exception:: AssertionError :module: .. index:: statement: assert Raised when an :keyword:`assert` statement fails. .. exception:: AttributeError :module: Raised when an attribute reference or assignment fails. (When an object does not support attribute references or attribute assignments at all, :exc:`TypeError` is raised.) .. exception:: BaseException :module: The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use :exc:`Exception`). If :func:`str` is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments. .. attribute:: args The tuple of arguments given to the exception constructor. Some built-in exceptions (like :exc:`OSError`) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message. .. exception:: EOFError :module: Raised when the :func:`input` function hits an end-of-file condition (EOF) without reading any data. The `read()` and `readline()` methods return an empty string when they hit EOF. .. data:: Ellipsis The same as ``...``. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types. .. exception:: Exception :module: All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class. .. data:: False :module: The false value of the :class:`bool` type. Assignments to ``False`` are illegal and raise a :exc:`SyntaxError`. .. exception:: GeneratorExit :module: Raised when a :term:`generator`;see :meth:`generator.close`. It directly inherits from :exc:`BaseException` instead of :exc:`Exception` since it is technically not an error. .. exception:: ImportError :module: Raised when an :keyword:`import` statement fails to find the module definition or when a ``from ... import`` fails to find a name that is to be imported. The :attr:`name` and :attr:`path` attributes can be set using keyword-only arguments to the constructor. When set they represent the name of the module that was attempted to be imported and the path to any file which triggered the exception, respectively. .. exception:: IndentationError :module: Base class for syntax errors related to incorrect indentation. This is a subclass of :exc:`SyntaxError`. .. exception:: IndexError :module: Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer, :exc:`TypeError` is raised.) .. exception:: KeyboardInterrupt :module: Raised when the user hits the interrupt key (:kbd:`Control-C`). During execution, a check for interrupts is made regularly. The exception inherits from :exc:`BaseException` so as to not be accidentally caught by code that catches :exc:`Exception` and thus prevent the interpreter from exiting. .. exception:: LogAccessError :module: Raised to indicate data could not be successfully retrieved from the Log. For instance, this could happen when an attempt is made to read new data and none remains. .. exception:: LookupError :module: The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This can be raised directly by :func:`codecs.lookup`. .. function:: MEASUREMENT(function) :module: The MEASUREMENT :term:`decorator` is used to indicate functions that will be used to process a measurement. Such a function should accept a single parameter containing the measured value and should return the processed value. Example:: @MEASUREMENT def convert_degF(degC): return (degC * 9.0/5.0) + 32.0 .. exception:: MemoryError :module: Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture, the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause. .. exception:: NameError :module: Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found. .. data:: None :module: The sole value of the type ``NoneType``. ``None`` is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to ``None`` are illegal and raise a :exc:`SyntaxError`. .. exception:: NotImplementedError :module: An exception raised if a non-supported feature was invoked. .. exception:: OSError([arg]) :module: .. index:: module: errno This exception is raised when a system function returns a system-related error, including I/O failures such as "file not found" or "disk full" (not for illegal argument types or other incidental errors). MicroPython doesn't implement the ``errno`` attribute, instead use the standard way to access exception arguments: ``exc.args[0]``. .. exception:: OverflowError :module: Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise :exc:`MemoryError` than give up). However, for historical reasons, OverflowError is sometimes raised for integers that are outside a required range. Because of the lack of standardization of floating point exception handling in C, most floating point operations are not checked. .. exception:: RuntimeError :module: Raised when an error is detected that doesn't fall in any of the other categories. The associated value is a string indicating what precisely went wrong. .. exception:: StopAsyncIteration :module: Must be raised by :meth:`__anext__` method of an :term:`asynchronous iterator` object to stop the iteration. .. exception:: StopIteration :module: Raised by built-in function :func:`next` and an :term:`iterator`\'s :meth:`~iterator.__next__` method to signal that there are no further items produced by the iterator. The exception object has a single attribute :attr:`value`, which is given as an argument when constructing the exception, and defaults to :const:`None`. When a :term:`generator` function returns, a new :exc:`StopIteration` instance is raised, and the value returned by the function is used as the :attr:`value` parameter to the constructor of the exception. .. exception:: SyntaxError :module: Raised when the parser encounters a syntax error. This may occur in an :keyword:`import` statement, in a call to the built-in functions :func:`exec` or :func:`eval`, or when reading the initial script or standard input (also interactively). .. exception:: SystemAbort :module: SystemAbort is raised if SystemExit is not sufficient to stop running threads. There does exist an opportuntity to handle a SystemAbort, but it is by design very limited in order to ensure that even a poorly designed threads can be stopped. .. exception:: SystemExit :module: This exception is raised by the :func:`sys.exit` function. It inherits from :exc:`BaseException` instead of :exc:`Exception` so that it is not accidentally caught by code that catches :exc:`Exception`. This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed. The constructor accepts the same optional argument passed to :func:`sys.exit`. If the value is an integer, it specifies the system exit status (passed to C's :c:func:`exit` function); if it is ``None``, the exit status is zero; if it has another type (such as a string), the object's value is printed and the exit status is one. A call to :func:`sys.exit` is translated into an exception so that clean-up handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be executed. .. function:: TASK(function) :module: The TASK :term:`decorator` is used to indicate functions that will be run by script tasks. Such a function has no parameters and returns no result. Example:: @TASK def reboot_at_midnight(): command_line("reboot") .. function:: TXFORMAT(function) :module: The TXFORMAT :term:`decorator` is used to indicate functions that will be run to perform custom formatting for telemetry. Such a function should accept a paramater containing the default formatted data and return the actual data to be transmitted. Example:: @TXFORMAT def append_test(msg): msg += "test" .. exception:: TimeoutError :module: Raised when a system function timed out at the system level. Corresponds to :c:data:`errno` ``ETIMEDOUT``. .. data:: True :module: The true value of the :class:`bool` type. Assignments to ``True`` are illegal and raise a :exc:`SyntaxError`. .. exception:: TypeError :module: Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch. .. exception:: UnicodeError :module: Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of :exc:`ValueError`. .. exception:: ValueError :module: Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as :exc:`IndexError`. .. exception:: ViperTypeError :module: The Viper code generator supports a restricted syntax and will raise this exception when it cannot figure out how to perform or does not support a conversion. .. exception:: ZeroDivisionError :module: Raised when the second argument of a division or modulo operation is zero.