Core language¶
Generated Wed 03 Jan 2024 12:07:50 UTC
Classes¶
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__
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
Method Resolution Order (MRO) is not compliant with CPython¶
Cause: Depth first non-exhaustive method resolution order
Workaround: 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
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
When inheriting from multiple classes super() only calls one class¶
Cause: See Method Resolution Order (MRO) is not compliant with CPython
Workaround: See 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__
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
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}
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
函数¶
Error messages for methods may display unexpected argument counts¶
Cause: MicroPython counts “self” as an argument.
Workaround: 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)
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
User-defined attributes for functions are not supported¶
Cause: MicroPython 已经对内存使用进行了高度优化
Workaround: Use external dictionary, e.g. FUNC_X[f] = 0.
参考代码
def f():
    pass
f.x = 0
print(f.x)
CPy 输出  | 
uPy 输出  | 
0
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
Generator¶
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
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
Runtime¶
Local variables aren’t included in locals() result¶
Cause: 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}
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
Code running in eval() function doesn’t have access to local variables¶
Cause: 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
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
import¶
__all__ is unsupported in __init__.py in MicroPython.¶
Cause: Not implemented.
Workaround: Manually import the sub-modules directly in __init__.py using from . import foo, bar.
参考代码
from modules3 import *
foo.hello()
CPy 输出  | 
uPy 输出  | 
hello
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
__path__ attribute of a package has a different type (single string instead of list of strings) in MicroPython¶
Cause: MicroPython does’t support namespace packages split across filesystem. Beyond that, MicroPython’s import system is highly optimized for minimal memory usage.
Workaround: 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/zhiwei/develop/delphinidae_V500R002/src/3dparty/source/micropython/tests/cpydiff/modules']
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
Failed to load modules are still registered as loaded¶
Cause: To make module handling more efficient, it’s not wrapped with exception handling.
Workaround: 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
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 | 
MicroPython does’t support namespace packages split across filesystem.¶
Cause: MicroPython’s import system is highly optimized for simplicity, minimal memory usage, and minimal filesystem search overhead.
Workaround: 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
 | 
/bin/sh: ../ports/unix/micropython: No such file or directory
 |