Kiểu dữ liệu tích hợp

Generated Thu 18 Jun 2026 14:23:40 UTC

Exception

Tất cả các ngoại lệ đều có thuộc tính valueerrno có thể đọc được, không chỉ StopIterationOSError.

Nguyên nhân: MicroPython được tối ưu hóa để giảm kích thước mã.

Cách khắc phục: Chỉ sử dụng value trên các ngoại lệ StopIteration, và errno trên các ngoại lệ OSError. Không sử dụng hoặc dựa vào các thuộc tính này trên các ngoại lệ khác.

Mã ví dụ:

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

Chuỗi ngoại lệ (exception chaining) chưa được triển khai

Mã ví dụ:

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:

Không hỗ trợ thuộc tính do người dùng định nghĩa cho các ngoại lệ tích hợp

Nguyên nhân: MicroPython được tối ưu hóa cao cho việc sử dụng bộ nhớ.

Cách khắc phục: Sử dụng các lớp con ngoại lệ do người dùng định nghĩa.

Mã ví dụ:

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'

Ngoại lệ trong điều kiện vòng lặp while có thể có số dòng không mong đợi

Nguyên nhân: Kiểm tra điều kiện được tối ưu hóa để xảy ra ở cuối thân vòng lặp, và số dòng đó được báo cáo.

Mã ví dụ:

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

Phương thức Exception.__init__ không tồn tại.

Nguyên nhân: Việc kế thừa các lớp native chưa được hỗ trợ đầy đủ trong MicroPython.

Cách khắc phục: Gọi bằng super() thay thế:

class A(Exception):
    def __init__(self):
        super().__init__()

Mã ví dụ:

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.

Mã ví dụ:

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

Gán slice mảng với RHS không được hỗ trợ

Mã ví dụ:

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

Đối tượng bytes hỗ trợ phương thức .format()

Nguyên nhân: MicroPython cố gắng trở thành một triển khai có tính nhất quán hơn, vì vậy nếu cả strbytes đều hỗ trợ __mod__() (toán tử %), thì việc hỗ trợ format() cho cả hai là hợp lý. Hỗ trợ cho __mod__ cũng có thể được biên dịch ra ngoài, chỉ còn lại format() để định dạng bytes.

Cách khắc phục: Nếu bạn quan tâm đến tính tương thích với CPython, đừng sử dụng .format() trên các đối tượng bytes.

Mã ví dụ:

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() với từ khóa chưa được triển khai

Cách khắc phục: Truyền encoding dưới dạng tham số vị trí, ví dụ: print(bytes('abc', 'utf-8'))

Mã ví dụ:

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

Đăng ký bytes với bước != 1 chưa được triển khai

Nguyên nhân: MicroPython được tối ưu hóa cao cho việc sử dụng bộ nhớ.

Cách khắc phục: Sử dụng vòng lặp tường minh cho thao tác rất hiếm này.

Mã ví dụ:

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

Nguyên nhân: MicroPython được tối ưu hóa cao cho việc sử dụng bộ nhớ.

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.

Mã ví dụ:

try:
    print(complex("1 1j"))
except ValueError:
    print("ValueError")

CPython output:

MicroPython output:

ValueError
(1+1j)

dict

Chế độ xem khóa của Dictionary không hoạt động như một set.

Nguyên nhân: Chưa được triển khai.

Cách khắc phục: Chuyển đổi khóa thành set một cách tường minh trước khi sử dụng các phép toán tập hợp.

Mã ví dụ:

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.

Cách khắc phục: Các đối tượng nên được bọc trong float(obj) để tương thích với CPython.

Mã ví dụ:

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

Phương thức bit_length không tồn tại.

Nguyên nhân: Phương thức bit_length chưa được triển khai.

Cách khắc phục: Tránh sử dụng phương thức này trên MicroPython.

Mã ví dụ:

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'

Không có chuyển đổi int cho các kiểu dẫn xuất từ int

Cách khắc phục: Tránh kế thừa các kiểu tích hợp trừ khi thực sự cần thiết. Ưu tiên https://en.wikipedia.org/wiki/Composition_over_inheritance .

Mã ví dụ:

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'

Phương thức to_bytes không triển khai tham số signed.

Nguyên nhân: Tham số chỉ theo từ khóa signed chưa được triển khai cho int.to_bytes().

Khi số nguyên là âm, MicroPython hoạt động giống như CPython int.to_bytes(..., signed=True)

Khi số nguyên không âm, MicroPython hoạt động giống như CPython int.to_bytes(..., signed=False).

(Sự khác biệt là tinh tế, nhưng trong CPython một số nguyên dương được chuyển đổi với signed=True có thể cần thêm một byte trong độ dài đầu ra, để phù hợp với bit dấu 0.)

Cách khắc phục: Cẩn thận khi gọi to_bytes() trên một giá trị số nguyên có thể là âm.

Mã ví dụ:

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

Xóa list với bước != 1 chưa được triển khai

Cách khắc phục: Sử dụng vòng lặp tường minh cho thao tác hiếm này.

Mã ví dụ:

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:

Lưu trữ slice list với giá trị không thể lặp ở RHS chưa được triển khai

Nguyên nhân: RHS bị giới hạn là tuple hoặc list

Cách khắc phục: Sử dụng list(<iter>) ở RHS để chuyển đổi iterable thành list

Mã ví dụ:

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

Lưu trữ list với bước != 1 chưa được triển khai

Cách khắc phục: Sử dụng vòng lặp tường minh cho thao tác hiếm này.

Mã ví dụ:

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 có thể trở nên không hợp lệ nếu đối tượng đích bị thay đổi kích thước

Nguyên nhân: CPython ngăn chặn đối tượng bytearray hoặc io.bytesIO thay đổi kích thước trong khi có đối tượng memoryview tham chiếu đến nó. MicroPython yêu cầu lập trình viên đảm bảo thủ công rằng một đối tượng không bị thay đổi kích thước trong khi bất kỳ memoryview nào tham chiếu đến nó.

Trong trường hợp xấu nhất, việc thay đổi kích thước một đối tượng là đích của memoryview có thể khiến các memoryview tham chiếu đến bộ nhớ đã được giải phóng không hợp lệ (lỗi use-after-free) và làm hỏng runtime MicroPython.

Cách khắc phục: Không thay đổi kích thước của bất kỳ đối tượng bytearray hoặc io.bytesIO nào đã có memoryview được gán cho nó.

Mã ví dụ:

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

Mã ví dụ:

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.

Mã ví dụ:

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.

Mã ví dụ:

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

Thuộc tính/đăng ký chưa được triển khai

Mã ví dụ:

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(...) với từ khóa chưa được triển khai

Cách khắc phục: Nhập trực tiếp định dạng encoding. Ví dụ: print(bytes('abc', 'utf-8'))

Mã ví dụ:

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() và str.rjust() chưa được triển khai

Nguyên nhân: MicroPython được tối ưu hóa cao cho việc sử dụng bộ nhớ. Có các cách khắc phục dễ dàng.

Cách khắc phục: Thay vì s.ljust(10) hãy dùng "%-10s" % s, thay vì s.rjust(10) hãy dùng "% 10s" % s. Ngoài ra, "{:<10}".format(s) hoặc "{:>10}".format(s).

Mã ví dụ:

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 làm đối số đầu tiên cho rsplit như str.rsplit(None, n) chưa được triển khai

Mã ví dụ:

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)

Đăng ký với bước != 1 chưa được triển khai

Mã ví dụ:

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

Tải tuple với bước != 1 chưa được triển khai

Mã ví dụ:

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