句法

Generated Thu 02 Sep 2021 01:44:06 UTC

运算符

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

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

解决方案: Do not rely on this behaviour if writing CPython compatible code.

样本代码:

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

CPy 输出:

uPy 输出:

  File "<stdin>", line 7
    print([i := -1 for i in range(4)])
             ^
SyntaxError: invalid syntax
																
[-1, -1, -1, -1]
																

Spaces

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

样本代码:

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 输出:

uPy 输出:

0
1
1
																
Should have worked
Should have worked
Should have worked
																

Unicode

Unicode 名称转义未被实现

样本代码:

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

CPy 输出:

uPy 输出:

a
																
NotImplementedError: unicode name escapes