This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions.

If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version.

builtins – builtin functions and exceptions

All builtin functions and exceptions are described here. They are also available via builtins module.

MicroPython builds are configurable, so some builtins and capabilities described below are not available on all builds. See the code or the MicroPython configuration macros page on the Wiki for details.

Functions and types

builtins.abs(x, /)

See CPython documentation: abs.

Return the absolute value of a number.

builtins.all(iterable, /)

See CPython documentation: all.

Return True if all elements of the iterable are true.

builtins.any(iterable, /)

See CPython documentation: any.

Return True if any element of the iterable is true.

builtins.bin(number, /)

See CPython documentation: bin.

Convert an integer to a binary string prefixed with 0b.

class builtins.bool(x=False, /)

See CPython documentation: bool.

A Boolean value, either True or False.

class builtins.bytearray(source=b'', encoding=None, errors=None, /)

See CPython documentation: bytearray.

Slice deletion or assignment with a step other than 1 is not implemented, and slice-assignment only accepts a value supporting the same operations as a list (not an arbitrary iterable).

class builtins.bytes(source=b'', encoding=None, errors=None, /)

See CPython documentation: bytes.

bytes(string, encoding) does not accept encoding as a keyword argument – pass it positionally. bytes objects also support .format() (in addition to %-formatting), and subscripting with a step other than 1 is not implemented.

decode(encoding='utf-8', errors='strict')

Decode the bytes object to a string using the specified encoding.

MicroPython supports the following encodings:

  • 'utf-8' or 'utf8' - UTF-8 encoding (default)

  • 'ascii' - ASCII encoding (subset of UTF-8)

The errors parameter controls how decoding errors are handled:

  • 'strict' - Raise a UnicodeError on invalid UTF-8 (default)

  • 'ignore' - Skip invalid bytes

  • 'replace' - Replace invalid bytes with U+FFFD ‘�’

Note

The 'ignore' and 'replace' error handlers are not available on all builds.

Example:

>>> b'\xc2\xa9 2024'.decode('utf-8')  # © symbol
'© 2024'
>>> b'hello\xffworld'.decode('utf-8', 'ignore')  # Skip invalid bytes
'helloworld'

Raises LookupError if the encoding is not supported, or UnicodeError if the data contains invalid UTF-8 and errors='strict'.

builtins.callable(obj)

See CPython documentation: callable.

Return whether the object appears to be callable.

builtins.chr(i, /)

See CPython documentation: chr.

Return the string of one character whose code point is the given integer. On builds without full Unicode support, only code points 0-255 are accepted.

builtins.classmethod(function, /)

See CPython documentation: classmethod.

Transform a method into a class method.

builtins.compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, /)

See CPython documentation: compile.

Compile source into a code object that can later be executed by exec or eval. The flags, dont_inherit and optimize arguments are accepted for CPython compatibility but are ignored.

class builtins.complex(real=0, imag=0, /)

See CPython documentation: complex.

Unlike CPython, the string parser also accepts a space (instead of a +) between the real and imaginary parts, e.g. complex("1 1j").

builtins.delattr(obj, name, /)

See CPython documentation: delattr.

The argument name should be a string, and this function deletes the named attribute from the object given by obj.

class builtins.dict(mapping_or_iterable=(), /, **kwarg)

See CPython documentation: dict.

The object returned by dict.keys() does not behave as a set view – set operations such as & or | against it are not supported.

builtins.dir()
builtins.dir(object, /)

See CPython documentation: dir.

Without an argument, return the names in the current local scope; with an argument, return the names available on that object. Unlike CPython, the returned list is not sorted.

builtins.divmod(x, y, /)

See CPython documentation: divmod.

Return the pair (x // y, x % y).

builtins.enumerate(iterable, start=0)

See CPython documentation: enumerate.

Return an iterator yielding pairs of index and value.

builtins.eval(expression, globals=None, locals=None, /)

See CPython documentation: eval.

Evaluate the given expression and return its value. At module scope this behaves as in CPython, but because MicroPython does not keep a symbolic namespace for a function’s local variables, code run by eval() inside a function cannot see that function’s locals: it effectively only has access to the module’s globals.

builtins.exec(source, globals=None, locals=None, /)

See CPython documentation: exec.

Execute the given source. Subject to the same local-scope limitation as eval().

builtins.filter(function, iterable, /)

See CPython documentation: filter.

Construct an iterator of the elements for which a function returns true.

class builtins.float(x=0.0, /)

See CPython documentation: float.

Unlike CPython, MicroPython implicitly converts an object that implements __float__() when it appears alongside a float in a math operation, instead of requiring an explicit float(obj) conversion.

class builtins.frozenset(iterable=(), /)

See CPython documentation: frozenset.

An immutable set.

builtins.getattr(object, name, [default, ]/)

See CPython documentation: getattr.

Return the value of a named attribute of an object, with an optional default.

builtins.globals()

See CPython documentation: globals.

Return the dictionary representing the current module’s global namespace.

builtins.hasattr(object, name, /)

See CPython documentation: hasattr.

Return whether the object has the given attribute.

builtins.hash(object, /)

See CPython documentation: hash.

Return the hash value of an object. Unlike CPython, the result is always truncated to a small, machine-word-sized integer, so hash values will generally not match CPython’s for the same object.

builtins.hex(number, /)

See CPython documentation: hex.

Convert an integer to a hexadecimal string prefixed with 0x.

builtins.id(object, /)

See CPython documentation: id.

Return an integer that is guaranteed to be constant and unique for the object during its lifetime.

builtins.input(prompt='', /)

See CPython documentation: input.

Read a line from input, optionally after printing a prompt.

class builtins.int(x=0, base=10, /)

See CPython documentation: int.

classmethod from_bytes(bytes, byteorder, /)

In MicroPython, byteorder parameter must be positional (this is compatible with CPython).

to_bytes(length=1, byteorder='big', *, signed=False)

Return an array of bytes representing an integer.

Unlike CPython, int does not implement the bit_length() method. Arithmetic on int subclasses does not convert the result back to that subclass.

builtins.isinstance(object, classinfo, /)

See CPython documentation: isinstance.

Return whether an object is an instance of a class (or one of a tuple of classes).

builtins.issubclass(class_, classinfo, /)

See CPython documentation: issubclass.

Return whether a class is a subclass of another class (or one of a tuple of classes).

builtins.iter(object, /)

See CPython documentation: iter.

Return an iterator for an object. Unlike CPython, the two-argument form iter(callable, sentinel) is not implemented.

builtins.len(s, /)

See CPython documentation: len.

Return the length of a container.

class builtins.list(iterable=(), /)

See CPython documentation: list.

Loading, storing or deleting a slice with a step other than 1 is not implemented, and slice-assignment only accepts a tuple or list on the right-hand side rather than an arbitrary iterable.

builtins.locals()

See CPython documentation: locals.

At module scope, behaves as in CPython. Inside a function, MicroPython compiles local variables to array slots rather than a symbolic namespace, so the dictionary returned by locals() does not include that function’s local variables.

builtins.map(function, *iterables)

See CPython documentation: map.

Apply a function to every item of an iterable, returning an iterator of the results.

builtins.max(iterable, /, *, key=None)
builtins.max(iterable, /, *, default, key=None)
builtins.max(arg1, arg2, /, *args, key=None)

See CPython documentation: max.

Return the largest item in an iterable, or the largest of two or more arguments.

class builtins.memoryview(obj, /)

See CPython documentation: memoryview.

Unlike CPython, MicroPython does not prevent a bytearray or io.BytesIO object from being resized while a memoryview still references it; doing so can leave the memoryview referencing invalid, freed memory.

builtins.min(iterable, /, *, key=None)
builtins.min(iterable, /, *, default, key=None)
builtins.min(arg1, arg2, /, *args, key=None)

See CPython documentation: min.

Return the smallest item in an iterable, or the smallest of two or more arguments.

next(iterator[, default], /).

See CPython documentation: next.

Retrieve the next item from an iterator.

Note

The two-argument form next(iterator, default) is not available on all builds.

class builtins.object

See CPython documentation: object.

User-defined classes do not support the __del__ special method. When subclassing a native type, methods inherited from that native base should not be used before super().__init__() has been called.

builtins.oct(number, /)

See CPython documentation: oct.

Convert an integer to an octal string prefixed with 0o.

builtins.open(name, mode='r', **kwargs)

See CPython documentation: open.

Open a file. See also io.open().

builtins.ord(c, /)

See CPython documentation: ord.

Return the code point of a one-character string.

builtins.pow(base, exp, mod=None, /)

See CPython documentation: pow.

Return base raised to the power exp, optionally modulo mod.

Note

The three-argument form is not available on all builds; where it is not available it raises NotImplementedError.

builtins.print(*objects, sep=' ', end='\n', file=sys.stdout)

See CPython documentation: print.

Print objects to a text stream, separated by sep and followed by end. Unlike CPython, the flush keyword argument is not supported.

class builtins.property(fget=None, fset=None, fdel=None, /, doc=None)

See CPython documentation: property.

In a subclass that overrides a property, accessing the property through super() returns the property object itself rather than invoking the getter and returning its value.

builtins.range(stop, /)
builtins.range(start, stop, step=1, /)

See CPython documentation: range.

start/stop/step values large enough to overflow the interpreter’s native integer type may raise OverflowError, or produce an incorrect len().

builtins.repr(object, /)

See CPython documentation: repr.

Return a printable representation of an object.

builtins.reversed(sequence, /)

See CPython documentation: reversed.

Return a reverse iterator.

builtins.round(number, [ndigits, ]/)

See CPython documentation: round.

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.

class builtins.set(iterable=(), /)

See CPython documentation: set.

Return a new set object, optionally with elements taken from iterable.

builtins.setattr(object, name, value, /)

See CPython documentation: setattr.

Set a named attribute on an object to a given value.

class builtins.slice

See CPython documentation: slice.

The slice builtin is the type that slice objects have, and cannot be instantiated directly.

builtins.sorted(iterable, /, *, key=None, reverse=False)

See CPython documentation: sorted.

Return a new sorted list from the items in an iterable.

builtins.staticmethod(function, /)

See CPython documentation: staticmethod.

Transform a method into a static method.

class builtins.str(object='', encoding=None, errors=None, /)

See CPython documentation: str.

A number of str methods and behaviours available in CPython are not implemented: str(bytes, encoding) does not accept encoding as a keyword argument, ljust()/rjust() do not exist, rsplit(None, n) is not supported, and subscripting with a step other than 1 is not implemented. str.format() does not support attribute/index access in replacement fields (e.g. "{a[0]}"), and does not reject the , grouping option for non-decimal presentation types like CPython does

encode(encoding='utf-8')

Encode the string to bytes using the specified encoding.

MicroPython supports the following encodings:

  • 'utf-8' or 'utf8' - UTF-8 encoding (default)

  • 'ascii' - ASCII encoding (subset of UTF-8)

Example:

>>> '© 2024'.encode('utf-8')  # Copyright symbol
b'\xc2\xa9 2024'

Raises LookupError if the encoding is not supported.

center(width)

Return a centered string of length width. Padding is done using spaces.

When full Unicode support is available, this method counts Unicode characters rather than bytes, ensuring proper alignment for multi-byte UTF-8 characters.

Example:

>>> 'café'.center(10)  # é is 2 bytes in UTF-8
'   café   '
builtins.sum(iterable, start=0, /)

See CPython documentation: sum.

Sum the items of an iterable, with an optional start value.

builtins.super()
builtins.super(type, obj)

See CPython documentation: super.

Only the zero-argument form (which may only be used inside a method body) and the two-argument form super(type, obj) are implemented; the single-argument “unbound” form super(type) is not supported. The method resolution order used to look up attributes through super() is a simplified, depth-first search rather than CPython’s C3 linearization. Therefore results can differ in non-trivial multiple-inheritance hierarchies, and calling super() from a class with multiple base classes only reaches one of them rather than cooperatively chaining through all of them.

class builtins.tuple(iterable=(), /)

See CPython documentation: tuple.

Subscripting with a step other than 1 is not implemented.

builtins.type(object, /)
builtins.type(name, bases, dict, /)

See CPython documentation: type.

Class creation follows the same simplified method resolution order described under super().

builtins.zip(*iterables)

See CPython documentation: zip.

Iterate over several iterables in parallel.

Exceptions

exception builtins.AssertionError

See CPython documentation: AssertionError.

exception builtins.AttributeError

See CPython documentation: AttributeError.

exception builtins.Exception

See CPython documentation: Exception.

All exceptions expose readable value and errno attributes, not just StopIteration.value and OSError.errno as in CPython – only rely on those two documented attributes for CPython compatibility.

Setting a new, user-defined attribute on a builtin exception instance is not supported; use an exception subclass instead.

Exception chaining (__context__/__cause__) is not implemented.

There is no unbound Exception.__init__ method to call directly on the class; use super().__init__() instead.

A subclass must also finish calling that __init__ before doing anything with self, such as raising it.

exception builtins.ImportError

See CPython documentation: ImportError.

exception builtins.IndexError

See CPython documentation: IndexError.

exception builtins.KeyboardInterrupt

See CPython documentation: KeyboardInterrupt.

See also in the context of Soft Bricking (failure to boot).

exception builtins.KeyError

See CPython documentation: KeyError.

exception builtins.MemoryError

See CPython documentation: MemoryError.

exception builtins.NameError

See CPython documentation: NameError.

exception builtins.NotImplementedError

See CPython documentation: NotImplementedError.

exception builtins.OSError

See CPython documentation: OSError. MicroPython does not implement the CPython-standard OSError subclasses (such as FileNotFoundError or PermissionError): every OS-level error raises a plain OSError, and callers should inspect its errno attribute rather than the exception type.

exception builtins.RuntimeError

See CPython documentation: RuntimeError.

exception builtins.StopIteration

See CPython documentation: StopIteration.

exception builtins.SyntaxError

See CPython documentation: SyntaxError.

exception builtins.SystemExit

See CPython documentation: SystemExit.

On non-embedded ports (i.e. Windows and Unix), an unhandled SystemExit exits the MicroPython process in a similar way to CPython.

On embedded ports, an unhandled SystemExit currently causes a Soft Reset of MicroPython.

exception builtins.TypeError

See CPython documentation: TypeError.

exception builtins.ValueError

See CPython documentation: ValueError.

exception builtins.ZeroDivisionError

See CPython documentation: ZeroDivisionError.