核心语言

Generated Thu 02 Sep 2021 01:44:06 UTC

f-strings don’t support concatenation with adjacent literals if the adjacent literals contain braces

原因: MicroPython is optimised for code space.

解决方案: Use the + operator between literal strings when either is an f-string

样本代码:

x = 1
print("aa" f"{x}")
print(f"{x}" "ab")
print("a{}a" f"{x}")
print(f"{x}" "a{}b")
											

CPy 输出:

uPy 输出:

  File "<stdin>", line 9
    print("aa" f"{x}")
               ^
SyntaxError: invalid syntax
															
aa1
1ab
Traceback (most recent call last):
  File "<stdin>", line 11, in <module>
IndexError: tuple index out of range
															

f-strings cannot support expressions that require parsing to resolve nested braces

原因: MicroPython is optimised for code space.

解决方案: Only use simple expressions inside f-strings

样本代码:

f'{"hello {} world"}'
f"{repr({})}"
											

CPy 输出:

uPy 输出:

  File "<stdin>", line 8
    f'{"hello {} world"}'
                        ^
SyntaxError: invalid syntax
															
Traceback (most recent call last):
  File "<stdin>", line 8
SyntaxError: invalid syntax
															

Raw f-strings are not supported

原因: MicroPython is optimised for code space.

样本代码:

rf"hello"
											

CPy 输出:

uPy 输出:

  File "<stdin>", line 8
    rf"hello"
            ^
SyntaxError: invalid syntax
															
Traceback (most recent call last):
  File "<stdin>", line 8
SyntaxError: raw f-strings are not supported
															

f-strings don’t support the !r, !s, and !a conversions

原因: MicroPython is optimised for code space.

解决方案: Use repr(), str(), and ascii() explictly.

样本代码:

class X:
    def __repr__(self):
        return "repr"
    def __str__(self):
        return "str"
print(f"{X()!r}")
print(f"{X()!s}")
											

CPy 输出:

uPy 输出:

  File "<stdin>", line 17
    print(f"{X()!r}")
                   ^
SyntaxError: invalid syntax
															
Traceback (most recent call last):
  File "<stdin>", line 17
SyntaxError: invalid syntax
															

Special method __del__ not implemented for user-defined classes

样本代码:

import gc
class Foo:
    def __del__(self):
        print("__del__")
f = Foo()
del f
gc.collect()
											

CPy 输出:

uPy 输出:

__del__
															

Method Resolution Order (MRO) is not compliant with CPython

原因: Depth first non-exhaustive method resolution order

解决方案: Avoid complex class hierarchies with multiple inheritance and complex method overrides. Keep in mind that many languages don’t support multiple inheritance at all.

样本代码:

class Foo:
    def __str__(self):
        return "Foo"
class C(tuple, Foo):
    pass
t = C((1, 2, 3))
print(t)
											

CPy 输出:

uPy 输出:

Foo
															
(1, 2, 3)
															

When inheriting from multiple classes super() only calls one class

原因: Method Resolution Order (MRO) is not compliant with CPython

解决方案: Method Resolution Order (MRO) is not compliant with CPython

样本代码:

class A:
    def __init__(self):
        print("A.__init__")
class B(A):
    def __init__(self):
        print("B.__init__")
        super().__init__()
class C(A):
    def __init__(self):
        print("C.__init__")
        super().__init__()
class D(B, C):
    def __init__(self):
        print("D.__init__")
        super().__init__()
D()
											

CPy 输出:

uPy 输出:

D.__init__
B.__init__
C.__init__
A.__init__
															
D.__init__
B.__init__
A.__init__
															

Calling super() getter property in subclass will return a property object, not the value

样本代码:

class A:
    @property
    def p(self):
        return {"a": 10}
class AA(A):
    @property
    def p(self):
        return super().p
a = AA()
print(a.p)
											

CPy 输出:

uPy 输出:

{'a': 10}
															
<property>
															

函数

Error messages for methods may display unexpected argument counts

原因: MicroPython 计数 self 作为自变量。

解决方案: Interpret error messages with the information above in mind.

样本代码:

try:
    [].append()
except Exception as e:
    print(e)
											

CPy 输出:

uPy 输出:

append() takes exactly one argument (0 given)
															
function takes 2 positional arguments but 1 were given
															

Function objects do not have the __module__ attribute

原因: MicroPython is optimized for reduced code size and RAM usage.

解决方案: 使用 sys.modules[function.__globals__['__name__']] for non-builtin modules.

样本代码:

def f():
    pass
print(f.__module__)
											

CPy 输出:

uPy 输出:

__main__
															
Traceback (most recent call last):
  File "<stdin>", line 13, in <module>
AttributeError: 'function' object has no attribute '__module__'
															

User-defined attributes for functions are not supported

原因: MicroPython 对内存用法高度优化。

解决方案: Use external dictionary, e.g. FUNC_X[f] = 0 .

样本代码:

def f():
    pass
f.x = 0
print(f.x)
											

CPy 输出:

uPy 输出:

0
															
Traceback (most recent call last):
  File "<stdin>", line 13, in <module>
AttributeError: 'function' object has no attribute 'x'
															

生成器

Context manager __exit__() not called in a generator which does not run to completion

样本代码:

class foo(object):
    def __enter__(self):
        print("Enter")
    def __exit__(self, *args):
        print("Exit")
def bar(x):
    with foo():
        while True:
            x += 1
            yield x
def func():
    g = bar(0)
    for _ in range(3):
        print(next(g))
func()
											

CPy 输出:

uPy 输出:

Enter
1
2
3
Exit
															
Enter
1
2
3
															

Runtime

Local variables aren’t included in locals() result

原因: MicroPython doesn’t maintain symbolic local environment, it is optimized to an array of slots. Thus, local variables can’t be accessed by a name.

样本代码:

def test():
    val = 2
    print(locals())
test()
											

CPy 输出:

uPy 输出:

{'val': 2}
															
{'test': <function test at 0x7fdda576e100>, '__name__': '__main__', '__file__': '<stdin>'}
															

Code running in eval() function doesn’t have access to local variables

原因: MicroPython doesn’t maintain symbolic local environment, it is optimized to an array of slots. Thus, local variables can’t be accessed by a name. Effectively, eval(expr) in MicroPython is equivalent to eval(expr, globals(), globals()) .

样本代码:

val = 1
def test():
    val = 2
    print(val)
    eval("print(val)")
test()
											

CPy 输出:

uPy 输出:

2
2
															
2
1
															

import

__all__ is unsupported in __init__.py in MicroPython.

原因: Not implemented.

解决方案: Manually import the sub-modules directly in __init__.py using from . import foo, bar .

样本代码:

from modules3 import *
foo.hello()
											

CPy 输出:

uPy 输出:

hello
															
Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
NameError: name 'foo' isn't defined
															

__path__ attribute of a package has a different type (single string instead of list of strings) in MicroPython

原因: MicroPython does’t support namespace packages split across filesystem. Beyond that, MicroPython’s import system is highly optimized for minimal memory usage.

解决方案: Details of import handling is inherently implementation dependent. Don’t rely on such details in portable applications.

样本代码:

import modules
print(modules.__path__)
											

CPy 输出:

uPy 输出:

['/home/micropython/micropython-docs/tests/cpydiff/modules']
															
../tests/cpydiff//modules
															

Failed to load modules are still registered as loaded

原因: To make module handling more efficient, it’s not wrapped with exception handling.

解决方案: Test modules before production use; during development, use del sys.modules["name"] , or just soft or hard reset the board.

样本代码:

import sys
try:
    from modules import foo
except NameError as e:
    print(e)
try:
    from modules import foo
    print("Should not get here")
except NameError as e:
    print(e)
											

CPy 输出:

uPy 输出:

foo
name 'xxx' is not defined
foo
name 'xxx' is not defined
															
foo
name 'xxx' isn't defined
Should not get here
															

MicroPython does’t support namespace packages split across filesystem.

原因: MicroPython’s import system is highly optimized for simplicity, minimal memory usage, and minimal filesystem search overhead.

解决方案: Don’t install modules belonging to the same namespace package in different directories. For MicroPython, it’s recommended to have at most 3-component module search paths: for your current application, per-user (writable), system-wide (non-writable).

样本代码:

import sys
sys.path.append(sys.path[1] + "/modules")
sys.path.append(sys.path[1] + "/modules2")
import subpkg.foo
import subpkg.bar
print("Two modules of a split namespace package imported")
											

CPy 输出:

uPy 输出:

Two modules of a split namespace package imported
															
Traceback (most recent call last):
  File "<stdin>", line 13, in <module>
ImportError: no module named 'subpkg.bar'