builtins
– 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¶
abs()
all()
any()
ascii()
bin()
bool()
bytearray()
bytes()
callable()
chr()
classmethod()
compile()
complex()
delattr()
dict()
dir()
divmod()
enumerate()
eval()
exec()
filter()
float()
format()
frozenset()
getattr()
globals()
hasattr()
hash()
help()
hex()
id()
input()
int()
isinstance()
issubclass()
iter()
len()
list()
locals()
map()
max()
memoryview()
min()
next()
object()
oct()
open()
ord()
pow()
print()
property()
range()
repr()
reversed()
round()
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
tuple()
type()
zip()
__import__()
List of constants, exceptions, and decorators¶
ArithmeticError
AssertionError
AttributeError
BaseException
EOFError
Ellipsis
Exception
False
GeneratorExit
ImportError
IndentationError
IndexError
KeyboardInterrupt
LogAccessError
LookupError
MEASUREMENT()
MemoryError
NameError
None
NotImplementedError
OSError
OverflowError
RuntimeError
StopAsyncIteration
StopIteration
SyntaxError
SystemAbort
SystemExit
TASK()
TXFORMAT()
TXMODE()
TimeoutError
True
TypeError
UnicodeError
ValueError
ViperTypeError
ZeroDivisionError
Functions¶
-
abs
(x)¶ 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.
-
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
-
any
(iterable)¶ Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
. Equivalent to:def any(iterable): for element in iterable: if element: return True return False
-
bin
(x)¶ 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'
-
bool
([x])¶ Return a Boolean value, i.e. one of
True
orFalse
. x is converted using the standard truth testing procedure. If x is false or omitted, this returnsFalse
; otherwise it returnsTrue
. Thebool
class is a subclass ofint
(see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances areFalse
andTrue
-
bytearray
([source])¶ Return a new array of bytes. The
bytearray
class is a mutable sequence of integers in the range 0 <= x < 256. , described in Mutable Sequence Types, as well as most methods that thebytes
type has, see Bytes and Bytearray Operations.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 Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.
-
bytes
([source])¶ Return a new
bytes
object, which is an immutable sequence of integers in the range0 <= x < 256
.bytes
is an immutable version ofbytearray
– it has the same non-mutating methods and the same indexing and slicing behavior.Accordingly, constructor arguments are interpreted as for
bytearray()
except a string literal is not allowed (use a bytes literal instead).See also Binary Sequence Types — bytes, bytearray, memoryview, Bytes, and Bytes and Bytearray Operations.
-
callable
(object)¶ Return
True
if the object argument appears callable,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__call__()
method.
-
chr
(i)¶ Return the string representing a character whose Unicode code point is the integer i. For example,
chr(97)
returns the string'a'
, whilechr(8364)
returns the string'€'
. This is the inverse oford()
.The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16).
ValueError
will be raised if i is outside that range.
-
classmethod
(function)¶ 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 decorator – see the description of function definitions in Function definitions for details.It can be called either on the class (such as
C.f()
) or on an instance (such asC().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
staticmethod()
in this section.For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.
-
compile
(source, filename, mode)¶ Compile the source into a code object. Code objects can be executed by
exec()
oreval()
. 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 (
'<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 thanNone
will be printed).This function raises
SyntaxError
if the compiled source is invalid, andValueError
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 thecode
module.
-
complex
([real[, imag]])¶ 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
int
andfloat
. If both arguments are omitted, returns0j
.The complex type is described in Numeric Types — int, float, complex.
-
dict
(**kwarg)¶ -
dict
(mapping, **kwarg) -
dict
(iterable, **kwarg) Create a new
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 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.
-
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.
The default
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.
-
divmod
(a, b)¶ 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 usuallymath.floor(a / b)
but may be 1 less than that. In any caseq * b + a % b
is very close to a, ifa % b
is non-zero it has the same sign as b, and0 <= abs(a % b) < abs(b)
.
-
enumerate
(iterable, start=0)¶ Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The
__next__()
method of the iterator returned byenumerate()
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
-
eval
(expression, globals=None, locals=None)¶ 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
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 whereeval()
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
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,eval()
’s return value will beNone
.Hints: dynamic execution of statements is supported by the
exec()
function. Theglobals()
andlocals()
functions returns the current global and local dictionary, respectively, which may be useful to pass around for use byeval()
orexec()
.
-
exec
(object[, globals[, locals]])¶ 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
return
andyield
statements may not be used outside of function definitions even within the context of code passed to theexec()
function. The return value isNone
.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 modulebuiltins
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 toexec()
.
-
filter
(function, iterable)¶ 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 notNone
and(item for item in iterable if item)
if function isNone
.
-
float
([x])¶ 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: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 Floating point literals. 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
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 Numeric Types — int, float, complex.
-
frozenset
([iterable])¶ Returns a new
frozenset
object, optionally with elements taken from iterable.frozenset
is a built-in class. Seefrozenset
and Set Types — set, frozenset for documentation about this class. Afrozenset
is an immutable version of a regularset
. 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
set
,list
,tuple
, anddict
classes, as well as thecollections
module.
-
getattr
(object, name[, default])¶ 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 tox.foobar
. If the named attribute does not exist, default is returned if provided, otherwiseAttributeError
is raised.
-
globals
()¶ 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).
-
hasattr
(object, name)¶ 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 callinggetattr(object, name)
and seeing whether it raises anAttributeError
or not.)
-
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
For objects with custom
__hash__()
methods, note thathash()
truncates the return value based on the bit width of the host machine. See__hash__()
for details.
-
help
([object])¶ Invoke the built-in help system which is very limited but can help to display some information about keywords, modules, functions, and methods.
-
hex
(x)¶ Convert an integer number to a lowercase hexadecimal string prefixed with “0x”, for example:
>>> hex(255) '0xff' >>> hex(-42) '-0x2a'
See also
int()
for converting a hexadecimal string to an integer.
-
id
(object)¶ 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
id()
value. This is the address of the object in memory.
-
input
([prompt])¶ 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,
EOFError
is raised. Example:>>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
-
int
(x=0)¶ 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,
bytes
, orbytearray
instance representing an 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, witha
toz
(orA
toZ
) having values 10 to 35. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with0b
/0B
,0o
/0O
, or0x
/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 thatint('010', 0)
is not legal, whileint('010')
is, as well asint('010', 8)
.The integer type is described in Numeric Types — int, float, complex.
-
isinstance
(object, classinfo)¶ Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or 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
TypeError
exception is raised.
-
issubclass
(class, classinfo)¶ Return true if class is a subclass (direct, indirect or 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
TypeError
exception is raised.
-
iter
(object)¶ Get an iterator from an object. object must be a collection object which supports the iteration protocol (the
__iter__()
method), or it must support the sequence protocol (the__getitem__()
method with integer arguments starting at0
). If it does not support either of those protocols,TypeError
is raised.See also Iterator Types.
-
len
(object)¶ 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).
-
list
([iterable])¶ Returns a new
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()
orlist(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']
andlist( (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
sorted()
built-in.Lists implement all of the common and mutable sequence operations. Lists also provide the following additional 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).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 ofNone
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
sorted()
to explicitly request a new sorted list instance).The
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.
- Using a pair of square brackets to denote the empty list:
-
locals
()¶ Update and return a dictionary representing the current local symbol table. Free variables are returned by
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.
-
map
(function, iterable, …)¶ 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.
-
max
(iterable)¶ -
max
(arg1, arg2, *args) 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 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]
.
-
memoryview
(obj)¶ Return a new
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 includebytes
andbytearray
.A
memoryview
has the notion of an element, which is the atomic memory unit handled by the originating object obj. For many simple types such asbytes
andbytearray
, an element is a single byte, but other types such asarray.array
may have bigger elements.len(view)
will return the number of elements in the view.A
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] <memoryview> >>> bytes(v[1:4]) b'bce'
-
min
(iterable)¶ -
min
(arg1, arg2, *args) 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 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]
.
-
next
(iterator)¶ Retrieve the next item from the iterator by calling its
__next__()
method. If the iterator is exhausted, otherwiseStopIteration
is raised.
-
object
()¶ Return a new featureless object.
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.
-
oct
(x)¶ Convert an integer number to an octal string prefixed with “0o”.
-
open
(file, mode=’r’, encoding=None)¶ Open file and return a corresponding file object. If the file cannot be opened, an
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 Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including
'b'
in the mode argument) return contents asbytes
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 asstr
, 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 file object returned by the
open()
function depends on the mode. Whenopen()
is used to open a file in a text mode ('w'
,'r'
,'wt'
,'rt'
, etc.), it returns a subclass ofio.TextIOBase
(specificallyio.TextIOWrapper
). When used to open a file in a binary mode with buffering, the returned class is a subclass ofio.BufferedIOBase
. The exact class varies: in read binary mode, it returns anio.BufferedReader
; in write binary and append binary modes, it returns anio.BufferedWriter
, and in read/write mode, it returns anio.BufferedRandom
. When buffering is disabled, the raw stream, a subclass ofio.RawIOBase
,io.FileIO
, is returned.See also the file handling modules, such as,
os
.
-
ord
(c)¶ Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example,
ord('a')
returns the integer97
andord('€')
(Euro sign) returns8364
. This is the inverse ofchr()
.
-
pow
(x, y[, z])¶ 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 formpow(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
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
returns100
, but10**-2
returns0.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.
-
print
(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)¶ 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
str()
does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also beNone
, which means to use the default values. If no objects are given,print()
will just write end.The file argument must be an object with a
write(string)
method; if it is not present orNone
,sys.stdout
will be used. Since printed arguments are converted to text strings,print()
cannot be used with binary mode file objects. For these, usefile.write(...)
instead.Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
-
property
(fget=None, fset=None, fdel=None, doc=None)¶ 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 anddel 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
property()
as a decorator:class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
The
@property
decorator turns thevoltage()
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
getter
,setter
, anddeleter
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
, andfdel
corresponding to the constructor arguments.
-
range
(stop)¶ -
range
(start, stop[, step]) Returns a
range
object containing an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.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 to0
. If step is zero,ValueError
is raised.For a positive step, the contents of a range
r
are determined by the formular[i] = start + step*i
wherei >= 0
andr[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 arei >= 0
andr[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
sys.maxsize
are permitted but some features (such aslen()
) may raiseOverflowError
.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 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).
-
repr
(object)¶ 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
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__repr__()
method.
-
reversed
(seq)¶ Return a reverse iterator. seq must be an object which has a
__reversed__()
method or supports the sequence protocol (the__len__()
method and the__getitem__()
method with integer arguments starting at0
).
-
round
(number[, ndigits])¶ 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
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, bothround(0.5)
andround(-0.5)
are0
, andround(1.5)
is2
). 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.
-
set
([iterable])¶ Return a new
set
object, optionally with elements taken from iterable.set
is a built-in class. Seeset
and Set Types — set, frozenset for documentation about this class.For other containers see the built-in
frozenset
,list
,tuple
, anddict
classes, as well as thecollections
module.
-
setattr
(object, name, value)¶ This is the counterpart of
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 tox.foobar = 123
.
-
slice
(stop)¶ -
slice
(start, stop[, step]) Return a slice object representing the set of indices specified by
range(start, stop, step)
. The start and step arguments default toNone
. Slice objects have read-only data attributesstart
,stop
andstep
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]
ora[start:stop, i]
.
-
sorted
(iterable[, key][, reverse])¶ 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 isNone
(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
functools.cmp_to_key()
to convert an old-style cmp function to a key function.The built-in
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 Sorting HOW TO.
-
staticmethod
(function)¶ 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 decorator – see the description of function definitions in Function definitions for details.It can be called either on the class (such as
C.f()
) or on an instance (such asC().f()
). The instance is ignored except for its class.Static methods in Python are similar to those found in Java or C++. Also see
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 The standard type hierarchy.
-
str
(object=’’)¶ -
str
(object=b’’, encoding=’utf-8’, errors=’strict’) Create a new
str
object from the given object. If object is not provided, returns the empty string. Otherwise, the behavior ofstr()
depends on whether encoding or errors is given, as follows.If neither encoding nor errors is given,
str(object)
returnsobject.__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__str__()
method, thenstr()
falls back to returningrepr(object)
.If at least one of encoding or errors is given, object should be a bytes-like object (e.g.
bytes
orbytearray
). In this case, if object is abytes
(orbytearray
) object, thenstr(bytes, encoding, errors)
is equivalent tobytes.decode(encoding, errors)
. Otherwise, the bytes object underlying the buffer object is obtained before callingbytes.decode()
. See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects.Passing a
bytes
object tostr()
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 Text Sequence Type — str and the String Methods section below. To output formatted strings, see the Format String Syntax section. In addition, see the Text Processing Services section.Note
Keyword arguments are not supported, encoding always defaults to “utf-8” regardless of what is passed, and errors are ignored.
-
sum
(iterable[, start])¶ 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
sum()
. The preferred, fast way to concatenate a sequence of strings is by calling''.join(sequence)
.
-
super
([type[, object-or-type]])¶ 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
super()
, see guide to using super().
-
tuple
([iterable])¶ Returns a
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
tuple()
built-in:tuple()
ortuple(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')
andtuple( [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, whilef((a, b, c))
is a function call with a 3-tuple as the sole argument.Tuples implement all of the common sequence operations.
- Using a pair of parentheses to denote the empty tuple:
-
type
(object)¶ -
type
(name, bases, dict) With one argument, return the type of an object. The return value is a type object and generally the same object as returned by
object.__class__
.The
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
class
statement. The name string is the class name and becomes the__name__
attribute; the bases tuple itemizes the base classes and becomes the__bases__
attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the__dict__
attribute. For example, the following two statements create identicaltype
objects:>>> class X: ... a = 1 ... >>> X = type('X', (object,), dict(a=1))
-
zip
(*iterables)¶ 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 iteratorn
times so that each output tuple has the result ofn
calls to the iterator. This has the effect of dividing the input into n-length chunks.zip()
should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables.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
-
__import__
(name, globals=None, locals=None, fromlist=(), level=0)¶ This function is invoked by the
import
statement. It can be replaced (by importing thebuiltins
module and assigning tobuiltins.__import__
) in order to change semantics of theimport
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
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__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
__import__()
returns the toplevel module here because this is the object that is bound to a name by theimport
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__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
¶ The base class for those built-in exceptions that are raised for various arithmetic errors:
OverflowError
,ZeroDivisionError
,FloatingPointError
-
exception
AttributeError
¶ Raised when an attribute reference or assignment fails. (When an object does not support attribute references or attribute assignments at all,
TypeError
is raised.)
-
exception
BaseException
¶ The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use
Exception
). Ifstr()
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.
-
exception
EOFError
¶ Raised when the
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.
-
builtins.
Ellipsis
¶ The same as
...
. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.
-
exception
Exception
¶ All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
-
False
¶ The false value of the
bool
type. Assignments toFalse
are illegal and raise aSyntaxError
.
-
exception
GeneratorExit
¶ Raised when a generator;see
generator.close()
. It directly inherits fromBaseException
instead ofException
since it is technically not an error.
-
exception
ImportError
¶ Raised when an
import
statement fails to find the module definition or when afrom ... import
fails to find a name that is to be imported.The
name
andpath
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
¶ Base class for syntax errors related to incorrect indentation. This is a subclass of
SyntaxError
.
-
exception
IndexError
¶ 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,
TypeError
is raised.)
-
exception
KeyboardInterrupt
¶ Raised when the user hits the interrupt key (
Control-C
). During execution, a check for interrupts is made regularly. The exception inherits fromBaseException
so as to not be accidentally caught by code that catchesException
and thus prevent the interpreter from exiting.
-
exception
LogAccessError
¶ 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
¶ The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid:
IndexError
,KeyError
. This can be raised directly bycodecs.lookup()
.
-
MEASUREMENT
(function)¶ The MEASUREMENT 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
¶ 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
¶ 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.
-
None
¶ 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 toNone
are illegal and raise aSyntaxError
.
-
exception
NotImplementedError
¶ An exception raised if a non-supported feature was invoked.
-
exception
OSError
([arg])¶ 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
¶ Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise
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
¶ 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
¶ Must be raised by
__anext__()
method of an asynchronous iterator object to stop the iteration.
-
exception
StopIteration
¶ Raised by built-in function
next()
and an iterator’s__next__()
method to signal that there are no further items produced by the iterator.The exception object has a single attribute
value
, which is given as an argument when constructing the exception, and defaults toNone
.When a generator function returns, a new
StopIteration
instance is raised, and the value returned by the function is used as thevalue
parameter to the constructor of the exception.
-
exception
SyntaxError
¶ Raised when the parser encounters a syntax error. This may occur in an
import
statement, in a call to the built-in functionsexec()
oreval()
, or when reading the initial script or standard input (also interactively).
-
exception
SystemAbort
¶ 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
¶ This exception is raised by the
sys.exit()
function. It inherits fromBaseException
instead ofException
so that it is not accidentally caught by code that catchesException
. 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 tosys.exit()
. If the value is an integer, it specifies the system exit status (passed to C’sexit()
function); if it isNone
, 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
sys.exit()
is translated into an exception so that clean-up handlers (finally
clauses oftry
statements) can be executed.
-
TASK
(function)¶ The TASK 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")
-
TXFORMAT
(function)¶ The TXFORMAT 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"
-
TXMODE
(function)¶ The TXMODE decorator is used to indicate functions that will be run to perform custom telemetry communications on a TCPIP socket.
It is possible to have the system connect to a TCPIP socket on a server, then hand over socket access to a Python function.
To use this feature, the Tx Mode setting needs to be set to Python TCPIP. In that mode, the system will connect to a server socket over TCPIP, using the Main Server, Server Port, Server Username, Server Password, and Use Certificate settings.
The telemetry system will get online and connect to the specified server. Once connected, the system will invoke the Python function that has been connected with the Tx Mode Function setting. After the function returns, the system will close the socket.
The telemetry setting Data Source controls whether formatted telemetry data or a file path is provided to the Python function.
The function takes in three parameters: commsocket, measurement_data, file_path.
The
commsocket
provides an open TCPIP socket to a server specified with XLink’s setup. It supports a limited subset of network socket communications such as send, recv, and settimeout.The parameter measurement_data is a string that is the formatted telemetry data which needs to be delivered to the server. This parameter is only relevant if Data Source is set to Measurement. The data is the result of standard telemetry formatting controlled by settings Format. If the Custom Script Format is On, another Python TXFORMAT function will create the data.
The parameter file_path is a string to a file path on XLink which needs to be delivered to the server. This parameter is only relevant if Data Source is set to File.
Either measurement_data or file_path should be used - one of them will be None based upon the Data Source setting.
An @TXMODE function should return 0 if everything went well, otherwise it can return 1 to indicate an error occurred and a retransmission should be performed (if possible).
@TXMODE was added with firmware version 8.70.
As the example demonstrates it’s preferable to send files a chunk at a time to keep memory usage reasonable.
Some possible uses for @TXMODE include:
- Create a custom HTTP message for your web server and process replies it sends
- Calculate a checksum on a file and append it at the end
- Transmit a camera image with an HTTP post and include custom headers with the file name, the current temperature, etc.
Example:
# this is an example of a raw protocol because all we do # is send either the measurement data or the file to the socket # without headers or additional manipulation # please note that the TCPIP SOCKET IS ALREADY OPENED before this function is called # the socket will automatically be closed after the function completes @TXMODE def my_tx_func(sock, measurement_data, file_path): if measurement_data: sock.send(measurement_data) if file_path: with open(file_path, "rb") as f: while True: data = f.read(1024) if not data: break sock.send(data) return 0
-
exception
TimeoutError
¶ Raised when a system function timed out at the system level. Corresponds to
errno
ETIMEDOUT
.
-
True
¶ The true value of the
bool
type. Assignments toTrue
are illegal and raise aSyntaxError
.
-
exception
TypeError
¶ 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
¶ Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of
ValueError
.
-
exception
ValueError
¶ 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
IndexError
.
-
exception
ViperTypeError
¶ 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
¶ Raised when the second argument of a division or modulo operation is zero.