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.

Syntax

Generated Wed 12 Jun 2024 04:26:44 UTC

Argument unpacking does not work if the argument being unpacked is the nth or greater argument where n is the number of bits in an MP_SMALL_INT.

Cause: The implementation uses an MP_SMALL_INT to flag args that need to be unpacked.

Workaround: Use fewer arguments.

Sample code:

def example(*args):
    print(len(args))


MORE = ["a", "b", "c"]

example(
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
    32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
    *MORE,
)

CPy output:

uPy output:

67
Traceback (most recent call last):
  File "<stdin>", line 21, in <module>
SyntaxError: too many args

Operators

MicroPython allows using := to assign to the variable of a comprehension, CPython raises a SyntaxError.

Cause: MicroPython is optimised for code size and doesn’t check this case.

Workaround: Do not rely on this behaviour if writing CPython compatible code.

Sample code:

print([i := -1 for i in range(4)])

CPy output:

uPy output:

  File "<stdin>", line 7
SyntaxError: assignment expression cannot rebind comprehension iteration variable 'i'
Traceback (most recent call last):
  File "<stdin>", line 7, in <listcomp>
SyntaxError: identifier redefined as global

Spaces

uPy requires spaces between literal numbers and keywords, CPy doesn’t

Sample code:

try:
    print(eval("1and 0"))
except SyntaxError:
    print("Should have worked")
try:
    print(eval("1or 0"))
except SyntaxError:
    print("Should have worked")
try:
    print(eval("1if 1else 0"))
except SyntaxError:
    print("Should have worked")

CPy output:

uPy output:

0
1
1
<string>:1: SyntaxWarning: invalid decimal literal
<string>:1: SyntaxWarning: invalid decimal literal
<string>:1: SyntaxWarning: invalid decimal literal
<string>:1: SyntaxWarning: invalid decimal literal
Should have worked
Should have worked
Should have worked

Unicode

Unicode name escapes are not implemented

Sample code:

print("\N{LATIN SMALL LETTER A}")

CPy output:

uPy output:

a
NotImplementedError: unicode name escapes