内置类型¶
Generated Fri 19 Jun 2026 22:08:45 UTC
异常¶
所有异常均具有可读的 value 和 errno 属性,而不仅限于 StopIteration 和 OSError。¶
原因: MicroPython 经过优化以减少代码体积。
解决方法: 仅在 StopIteration 异常上使用 value,仅在 OSError 异常上使用 errno。不要在其他异常上使用或依赖这些属性。
示例代码:
e = Exception(1)
print(e.value)
print(e.errno)
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
AttributeError: 'Exception' object has no attribute 'value'
| 1
1
|
未实现异常链¶
示例代码:
try:
raise TypeError
except TypeError:
raise ValueError
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
TypeError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
ValueError
| Traceback (most recent call last):
File "<stdin>", line 11, in <module>
ValueError:
|
不支持内置异常的用户自定义属性¶
原因: MicroPython 针对内存使用进行了高度优化。
解决方法: 使用用户自定义的异常子类。
示例代码:
e = Exception()
e.x = 0
print(e.x)
CPython output: | MicroPython output: |
0
| Traceback (most recent call last):
File "<stdin>", line 9, in <module>
AttributeError: 'Exception' object has no attribute 'x'
|
while 循环条件中的异常可能报告意外的行号¶
原因: 条件检查被优化为在循环体末尾执行,因此报告的是该处的行号。
示例代码:
l = ["-foo", "-bar"]
i = 0
while l[i][0] == "-":
print("iter")
i += 1
CPython output: | MicroPython output: |
iter
iter
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
IndexError: list index out of range
| iter
iter
Traceback (most recent call last):
File "<stdin>", line 13, in <module>
IndexError: list index out of range
|
Exception.__init__ 方法不存在。¶
原因: MicroPython 不完全支持对原生类进行子类化。
解决方法: 改用 super() 调用::
class A(Exception):
def __init__(self):
super().__init__()
示例代码:
class A(Exception):
def __init__(self):
Exception.__init__(self)
a = A()
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 18, in <module>
File "<stdin>", line 15, in __init__
AttributeError: type object 'Exception' has no attribute '__init__'
|
OSError¶
OSError constructor returns a plain OSError for all errno values, rather than a relevant subtype.¶
Cause: MicroPython does not include the CPython-standard OSError subclasses.
Workaround: Catch OSError and use its errno attribute to discriminate the cause.
示例代码:
import errno
errno_list = [ # i.e. the set implemented by micropython
errno.EPERM,
errno.ENOENT,
errno.EIO,
errno.EBADF,
errno.EAGAIN,
errno.ENOMEM,
errno.EACCES,
errno.EEXIST,
errno.ENODEV,
errno.EISDIR,
errno.EINVAL,
errno.EOPNOTSUPP,
errno.EADDRINUSE,
errno.ECONNABORTED,
errno.ECONNRESET,
errno.ENOBUFS,
errno.ENOTCONN,
errno.ETIMEDOUT,
errno.ECONNREFUSED,
errno.EHOSTUNREACH,
errno.EALREADY,
errno.EINPROGRESS,
]
def errno_output_type(n):
try:
raise OSError(n, "")
except OSError as e:
return f"{type(e).__name__}"
except Exception as e:
return f"non-OSError {type(e).__name__}"
else:
return "no error"
for n in errno_list:
print(errno.errorcode[n], "=", errno_output_type(n))
CPython output: | MicroPython output: |
EPERM = PermissionError
ENOENT = FileNotFoundError
EIO = OSError
EBADF = OSError
EAGAIN = BlockingIOError
ENOMEM = OSError
EACCES = PermissionError
EEXIST = FileExistsError
ENODEV = OSError
EISDIR = IsADirectoryError
EINVAL = OSError
ENOTSUP = OSError
EADDRINUSE = OSError
ECONNABORTED = ConnectionAbortedError
ECONNRESET = ConnectionResetError
ENOBUFS = OSError
ENOTCONN = OSError
ETIMEDOUT = TimeoutError
ECONNREFUSED = ConnectionRefusedError
EHOSTUNREACH = OSError
EALREADY = BlockingIOError
EINPROGRESS = BlockingIOError
| EPERM = OSError
ENOENT = OSError
EIO = OSError
EBADF = OSError
EAGAIN = OSError
ENOMEM = OSError
EACCES = OSError
EEXIST = OSError
ENODEV = OSError
EISDIR = OSError
EINVAL = OSError
EOPNOTSUPP = OSError
EADDRINUSE = OSError
ECONNABORTED = OSError
ECONNRESET = OSError
ENOBUFS = OSError
ENOTCONN = OSError
ETIMEDOUT = OSError
ECONNREFUSED = OSError
EHOSTUNREACH = OSError
EALREADY = OSError
EINPROGRESS = OSError
|
bytearray¶
不支持的右值数组切片赋值¶
示例代码:
b = bytearray(4)
b[0:1] = [1, 2]
print(b)
CPython output: | MicroPython output: |
bytearray(b'\x01\x02\x00\x00\x00')
| Traceback (most recent call last):
File "<stdin>", line 9, in <module>
NotImplementedError: array/bytes required on right side
|
bytes¶
bytes 对象支持 .format() 方法¶
原因: MicroPython 致力于提供更统一的实现,因此若 str 和 bytes 均支持 __mod__()(即 % 运算符),则为两者同时支持 format() 也是合理的。__mod__ 的支持也可在编译时去除,此时仅保留 format() 用于 bytes 格式化。
解决方法: 若需与 CPython 兼容,请勿对 bytes 对象使用 .format()。
示例代码:
print(b"{}".format(1))
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
AttributeError: 'bytes' object has no attribute 'format'
| b'1'
|
未实现带关键字参数的 bytes()¶
解决方法: 将编码作为位置参数传入,例如 print(bytes('abc', 'utf-8'))。
示例代码:
print(bytes("abc", encoding="utf8"))
CPython output: | MicroPython output: |
b'abc'
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: keyword argument(s) not implemented - use normal args instead
|
未实现步长不为 1 的 bytes 下标访问¶
原因: MicroPython 针对内存使用进行了高度优化。
解决方法: 对这种极少见的操作使用显式循环。
示例代码:
print(b"123"[0:3:2])
CPython output: | MicroPython output: |
b'13'
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
|
complex¶
MicroPython's complex() accepts certain incorrect values that CPython rejects¶
原因: MicroPython 针对内存使用进行了高度优化。
Workaround: Do not use non-standard complex literals as argument to complex()
MicroPython's complex() function accepts literals that contain a space and no sign between the real and imaginary parts, and interprets it as a plus.
示例代码:
try:
print(complex("1 1j"))
except ValueError:
print("ValueError")
CPython output: | MicroPython output: |
ValueError
| (1+1j)
|
dict¶
字典键视图的行为与集合不一致。¶
原因: 未实现。
解决方法: 在使用集合操作前,先将键显式转换为集合。
示例代码:
print({1: 2, 3: 4}.keys() & {1})
CPython output: | MicroPython output: |
{1}
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
TypeError: unsupported types for __and__: 'dict_view', 'set'
|
float¶
MicroPython allows implicit conversion of objects in maths operations while CPython does not.¶
解决方法: 为与 CPython 兼容,应将对象包装在 float(obj) 中。
示例代码:
class Test:
def __float__(self):
return 0.5
print(2.0 * Test())
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 14, in <module>
TypeError: unsupported operand type(s) for *: 'float' and 'Test'
| 1.0
|
int¶
bit_length 方法不存在。¶
原因: bit_length 方法未实现。
解决方法: 在 MicroPython 上避免使用该方法。
示例代码:
x = 255
print("{} is {} bits long.".format(x, x.bit_length()))
CPython output: | MicroPython output: |
255 is 8 bits long.
| Traceback (most recent call last):
File "<stdin>", line 9, in <module>
AttributeError: 'int' object has no attribute 'bit_length'
|
int 派生类型无法进行 int 转换¶
解决方法: 除非确实必要,否则避免对内置类型进行子类化。推荐参考 https://en.wikipedia.org/wiki/Composition_over_inheritance 。
示例代码:
class A(int):
__add__ = lambda self, other: A(int(self) + other)
a = A(42)
print(a + a)
CPython output: | MicroPython output: |
84
| Traceback (most recent call last):
File "<stdin>", line 14, in <module>
File "<stdin>", line 10, in <lambda>
TypeError: unsupported types for __radd__: 'int', 'int'
|
to_bytes 方法未实现 signed 参数。¶
原因: int.to_bytes() 未实现仅关键字参数 signed。
当整数为负数时,MicroPython 的行为与 CPython 的 int.to_bytes(..., signed=True) 相同。
当整数为非负数时,MicroPython 的行为与 CPython 的 int.to_bytes(..., signed=False) 相同。
(差异较为细微:在 CPython 中,使用 signed=True 转换正整数时,输出长度可能需要多一个字节,以容纳符号位 0。)
解决方法: 对可能为负数的整数调用 to_bytes() 时请格外注意。
示例代码:
x = -1
print(x.to_bytes(1, "big"))
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 16, in <module>
OverflowError: can't convert negative int to unsigned
| b'\xff'
|
list¶
未实现步长不为 1 的列表删除¶
解决方法: 对这种少见的操作使用显式循环。
示例代码:
l = [1, 2, 3, 4]
del l[0:4:2]
print(l)
CPython output: | MicroPython output: |
[2, 4]
| Traceback (most recent call last):
File "<stdin>", line 9, in <module>
NotImplementedError:
|
未实现右值为非可迭代对象的列表切片存储¶
原因: 右值仅限于元组或列表。
解决方法: 在右值上使用 list(<iter>) 将可迭代对象转换为列表。
示例代码:
l = [10, 20]
l[0:1] = range(4)
print(l)
CPython output: | MicroPython output: |
[0, 1, 2, 3, 20]
| Traceback (most recent call last):
File "<stdin>", line 9, in <module>
TypeError: object 'range' isn't a tuple or list
|
未实现步长不为 1 的列表存储¶
解决方法: 对这种少见的操作使用显式循环。
示例代码:
l = [1, 2, 3, 4]
l[0:4:2] = [5, 6]
print(l)
CPython output: | MicroPython output: |
[5, 2, 6, 4]
| Traceback (most recent call last):
File "<stdin>", line 9, in <module>
NotImplementedError:
|
memoryview¶
若目标对象被调整大小,memoryview 可能失效¶
原因: CPython 在存在引用该对象的 memoryview 时,会阻止 bytearray 或 io.bytesIO 对象改变大小。MicroPython 则要求程序员手动确保在任何 memoryview 引用对象期间不调整其大小。
在最坏情况下,调整 memoryview 目标对象的大小可能导致 memoryview 引用已释放的无效内存(即释放后使用漏洞),进而破坏 MicroPython 运行时。
解决方法: 不要改变任何已被 memoryview 引用的 bytearray 或 io.bytesIO 对象的大小。
示例代码:
b = bytearray(b"abcdefg")
m = memoryview(b)
b.extend(b"hijklmnop")
print(b, bytes(m))
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 12, in <module>
BufferError: Existing exports of data: object cannot be re-sized
| bytearray(b'abcdefghijklmnop') b'abcdefg'
|
range¶
Range objects with large start or stop arguments misbehave.¶
Cause: Intermediate calculations overflow the C mp_int_t type
Workaround: Avoid using such ranges
示例代码:
from sys import maxsize
# A range including `maxsize-1` cannot be created
try:
print(range(-maxsize - 1, 0))
except OverflowError:
print("OverflowError")
# A range with `stop-start` exceeding sys.maxsize has incorrect len(), while CPython cannot calculate len().
try:
print(len(range(-maxsize, maxsize)))
except OverflowError:
print("OverflowError")
# A range with `stop-start` exceeding sys.maxsize has incorrect len()
try:
print(len(range(-maxsize, maxsize, maxsize)))
except OverflowError:
print("OverflowError")
CPython output: | MicroPython output: |
range(-9223372036854775808, 0)
OverflowError
2
| OverflowError
0
0
|
str¶
MicroPython accepts the "," grouping option with any radix, unlike CPython¶
Cause: To reduce code size, MicroPython does not issue an error for this combination
Workaround: Do not use a format string like {:,b} if CPython compatibility is required.
示例代码:
try:
print("{:,b}".format(99))
except ValueError:
print("ValueError")
try:
print("{:,x}".format(99))
except ValueError:
print("ValueError")
try:
print("{:,o}".format(99))
except ValueError:
print("ValueError")
CPython output: | MicroPython output: |
ValueError
ValueError
ValueError
| 110,0011
63
143
|
MicroPython accepts but does not properly implement the "," or "_" grouping character for float values¶
Cause: To reduce code size, MicroPython does not implement this combination. Grouping characters will not appear in the number's significant digits and will appear at incorrect locations in leading zeros.
Workaround: Do not use a format string like {:,f} if exact CPython compatibility is required.
示例代码:
print("{:,f}".format(3141.159))
print("{:_f}".format(3141.159))
print("{:011,.2f}".format(3141.159))
print("{:011_.2f}".format(3141.159))
CPython output: | MicroPython output: |
3,141.159000
3_141.159000
0,003,141.16
0_003_141.16
| 3141.159000
3141.159000
000,3141.16
0_003141.16
|
属性/下标访问未实现¶
示例代码:
print("{a[0]}".format(a=[1, 2]))
CPython output: | MicroPython output: |
1
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: attributes not supported
|
未实现带关键字参数的 str()¶
解决方法: 直接传入编码格式,例如 print(bytes('abc', 'utf-8'))。
示例代码:
print(str(b"abc", encoding="utf8"))
CPython output: | MicroPython output: |
abc
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: keyword argument(s) not implemented - use normal args instead
|
str.ljust() 和 str.rjust() 未实现¶
原因: MicroPython 针对内存使用进行了高度优化,且存在简便的替代方案。
解决方法: 用 "%-10s" % s 替代 s.ljust(10),用 "% 10s" % s 替代 s.rjust(10)。也可使用 "{:<10}".format(s) 或 "{:>10}".format(s)。
示例代码:
print("abc".ljust(10))
CPython output: | MicroPython output: |
abc
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
AttributeError: 'str' object has no attribute 'ljust'
|
未实现以 None 作为 rsplit 首参数,例如 str.rsplit(None, n)¶
示例代码:
print("a a a".rsplit(None, 1))
CPython output: | MicroPython output: |
['a a', 'a']
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: rsplit(None,n)
|
步长不为 1 的下标访问尚未实现¶
示例代码:
print("abcdefghi"[0:9:2])
CPython output: | MicroPython output: |
acegi
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
|
tuple¶
未实现步长不为 1 的元组读取¶
示例代码:
print((1, 2, 3, 4)[0:4:2])
CPython output: | MicroPython output: |
(1, 3)
| Traceback (most recent call last):
File "<stdin>", line 8, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
|