MicroPython Standard Library

Contents

Introduction

Module refers to any MicroPython file saved with the .py extension. Modules contain code such as functions, classes and statements.

The term Library is used to refer to a collection of modules that are used repeatedly in various programs without the need of writing them from scratch. The components of libraries and modules can be imported and used within other programs, thus promoting the reuse of code.

Python comes installed with a standard library that simplifies common programming tasks. As MicroPython is a slimmed down Python specifically designed for the programming of microcontrollers it implements many parts of the Python standard library but omits components that are irrelevant to this purpose.

Standard Library Modules

Many of the standard library modules provided by MicroPython don't contain all objects as defined in the full language definition. These modules are usually prefixed with a ‘u’ literally meaning ‘micro’.

A list of modules available in the MicroPython implementation being used can easily be obtained by entering help('modules') into the REPL

__main__       machine        power          urandom 
antigravity    math           radio          ustruct
audio          microbit       speech         usys
builtins       micropython    this           utime
gc             music          uarray         
log           neopixel        ucollections
love          os              uerrno
Plus any modules on the filesystem
          

If your list modules doesn't include all that appear in the above list then your micro:bit has an out-of-date MicroPython runtime. This tutorial explains how to update the runtime on your device.

A list of objects within any module can be obtained by using the following syntax in the REPL:


import module
dir(module)
          

For example:


import math
dir(math)

['__class__', '__name__', 'pow', 'e', 'acos',
'asin', 'atan', 'atan2', 'ceil', 'copysign',
'cos', 'degrees', 'exp', 'fabs', 'floor',
'fmod', 'frexp', 'isfinite', 'isinf', 'isnan',
'ldexp', 'log', 'modf', 'pi', 'radians', 'sin',
'sqrt', 'tan', 'trunc'] 
          

The standard Python modules available in MicroPython are described in the following table.

Table 1: Standard Library Modules
Module Description
antigravity[1] An ‘Easter egg’ with no practical functionality
builtins[2] Provides direct access to all ‘built-in’ identifiers of MicroPython
gc[3] Provides ability to manually control garbage collection. This level of control is rarely need.
math[4] Provides useful mathematical functions
os[5] Provides basic operating system services
this[1] No practical functionality; just a fun gimmick demonstrating ROT13 encoding
uarray[6]
(array)
Defines an object that compactly represents an array of elements all of the same datatype and numerical.
ucollections[7]
(collections)
Provides the function namedtuple() and the OrderDict dictionary subclass.
uerrno[1]
(errno)
System error codes
urandom[A]
(random)
Methods to generates pseudo-random numbers. These methods are very useful in simulations when artificially generated data is required for test purposes.
ustruct[8]
(struct)
Performs conversions between Python values and C structs represented as Python bytes objects.
usys[9]
(sys)
Provides system specific functions
utime[A]
(time)
Provides time related functions. This module is widely used when interfacing with sensors where driver classes need to perform very exacting timing sequences.

MicroPython and micro:bit Specific Modules

The next table lists modules specific to MicroPython and the micro:bit. Detailed documentation for these modules can be found here.

Another excellent site with heaps of useful information and tips for MicroPython programming of the micro:bit can be found here. The content on this site very much complements this series on the MicroPython language. There are many MicroPython examples, with clear explanation, given for accessing the micro:bit's hardware.

Table 2: MicroPython and micro:bit Specific Modules
Module Description
audio Play sounds on an attached speaker
love Flashes a heart-like pattern on the micro:bit's LED array
machine Low-level access to the micro:bit's hardware.
microbit[10] Interacts with the hardware on the micro:bit board
micropython Provides access and control to MicroPython internals
music Play music to attached headphones
neopixel Controls a NeoPixel string of RGB LEDs
radio Enables communication between two or more micro:bit boards
speech Text strings are converted to audio speech

Importing Modules

Before a program can use the functionality from another module it must be be imported. The syntax has two forms.

The simplest form:


Syntax 1

import module

Alternatively:

import module as name

Parameter
   module : Name of the module to be
            accessed in the program.
    name :  Synonym for the module name.

Example:
import math
print(math.sqrt(5))  ⇒ 2.236068 

import math as m
print(m.log(5))  ⇒ 1.609438

          

A much richer and more useful syntax:


Syntax 2

from module import funct-1[, funct-2,… funct-n]

Parameters
   module : Name of the module to be
            accessed in the program.
    funct-1, funct-2, funct-n
       : One or more functions from module
        to be referenced in the program.

Example:
from math import sqrt, sin
print(sqrt(5))  ⇒ 2.236068
print(sin(10))  ⇒ -0.5440211

          

Enter the following code into the Mu Editor, save and flash to the micro:bit.

Example 1 - A Common Mistake



 # Calculate a square root

a = 144
b = math.sqrt(a)
print("Square root of", a, "=", b)
          

Output:


  File "main.py", line 4, in module
NameError: name 'math' isn't defined
          

MicroPython returns an error in this case because the math module hasn't been imported.

Example 2 - Syntax 1


# Calculate a square root

import math
a = 144
b = math.sqrt(a)
print("Square root of", a, "=", b)
          

Output:


Square root of 144 = 12.0
          

This example uses Syntax 1 with the simplest form of import. Note that in this case a reference to the module must be prefixed when using a function i.e. module.function()

Example 3 - Syntax 2


# Calculate a square root

from math import sqrt
a = 144
b = sqrt(a)
print("Square root of", a, "=", b)
          

Output:


Square root of 144 = 12.0
          

This example uses Syntax 2; making reference directly to the function sqrt() in the math module. From that point on the function can be called in the code without the full math.sqrt() qualification. In fact if math.sqrt() is used then the program will throw an error (NameError: name 'math' isn't defined)!