內建型別

Generated Fri 19 Jun 2026 22:08:45 UTC

例外

所有例外皆具有可讀取的 valueerrno 屬性,不只限於 StopIterationOSError

原因: 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 致力於更一致的實作,因此若 strbytes 都支援 __mod__()(即 % 運算子),則兩者同時支援 format() 也合乎邏輯。__mod__ 的支援亦可在編譯時移除,屆時 bytes 格式化僅剩 format()

因應方式: 若需要與 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 的型別進行整數轉換

因應方式: 除非確有必要,否則避免繼承內建型別。建議優先採用 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:

未實作右側為非可迭代物件的串列切片儲存

原因: 右側僅限為 tuple 或 list。

因應方式: 在右側使用 list(<iter>) 將可迭代物件轉換為 list。

範例程式碼::

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 會在存在參照至 bytearrayio.bytesIO 物件的 memoryview 時,阻止該物件改變大小。MicroPython 則要求程式設計師自行確保在任何 memoryview 參照物件期間不重新調整其大小。

在最壞的情況下,重新調整 memoryview 目標物件的大小可能導致 memoryview 參照已釋放的無效記憶體(釋放後使用漏洞),並損毀 MicroPython 執行環境。

因應方式: 請勿變更已有 memoryview 指向的 bytearrayio.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 的 tuple 讀取

範例程式碼::

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