ประเภทข้อมูลในตัว

Generated Thu 18 Jun 2026 19:58:13 UTC

Exception

ข้อยกเว้นทั้งหมดมีแอตทริบิวต์ value และ errno ที่อ่านได้ ไม่ใช่เฉพาะ StopIteration และ OSError เท่านั้น

สาเหตุ: MicroPython ได้รับการปรับให้เหมาะสมเพื่อลดขนาดโค้ด

วิธีแก้ไข: ใช้ value เฉพาะกับข้อยกเว้น StopIteration และ errno เฉพาะกับข้อยกเว้น OSError เท่านั้น อย่าใช้หรือพึ่งพาแอตทริบิวต์เหล่านี้กับข้อยกเว้นอื่น

โค้ดตัวอย่าง:

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

ยังไม่รองรับการเชื่อมโยงข้อยกเว้น (Exception chaining)

โค้ดตัวอย่าง:

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 loop อาจรายงานหมายเลขบรรทัดที่ไม่คาดคิด

สาเหตุ: การตรวจสอบเงื่อนไขได้รับการปรับให้เหมาะสมให้เกิดขึ้นที่ส่วนท้ายของ loop body และจะรายงานหมายเลขบรรทัดนั้น

โค้ดตัวอย่าง:

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__

สาเหตุ: การสืบทอดคลาส native ไม่ได้รับการสนับสนุนอย่างสมบูรณ์ใน 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

ไม่รองรับการกำหนดค่าสไลส์ array ด้วย RHS ที่ไม่รองรับ

โค้ดตัวอย่าง:

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 มุ่งเน้นการเป็น implementation ที่สม่ำเสมอมากขึ้น ดังนั้นหากทั้ง str และ bytes รองรับ __mod__() (ตัวดำเนินการ %) ก็สมเหตุสมผลที่จะรองรับ format() สำหรับทั้งสองด้วย นอกจากนี้ยังสามารถคอมไพล์ออกการรองรับ __mod__ ซึ่งจะเหลือเฉพาะ format() สำหรับการจัดรูปแบบ bytes

วิธีแก้ไข: หากต้องการความเข้ากันได้กับ CPython อย่าใช้ .format() กับออบเจ็กต์ bytes

โค้ดตัวอย่าง:

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() พร้อม keywords

วิธีแก้ไข: ส่ง encoding เป็นพารามิเตอร์ตำแหน่ง เช่น 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

ยังไม่รองรับการสมัครสมาชิก Bytes ที่มี step != 1

สาเหตุ: MicroPython ได้รับการปรับให้เหมาะสมอย่างมากสำหรับการใช้หน่วยความจำ

วิธีแก้ไข: ใช้ loop แบบชัดเจนสำหรับการดำเนินการที่หายากมากนี้

โค้ดตัวอย่าง:

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

มุมมองคีย์ของ Dictionary ไม่ทำงานเหมือน set

สาเหตุ: ยังไม่ได้รับการรองรับ

วิธีแก้ไข: แปลงคีย์เป็น set อย่างชัดเจนก่อนใช้การดำเนินการ set

โค้ดตัวอย่าง:

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.

วิธีแก้ไข: ออบเจ็กต์ควรถูกห่อด้วย float(obj) เพื่อความเข้ากันได้กับ CPython

โค้ดตัวอย่าง:

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

สาเหตุ: พารามิเตอร์ keyword-only signed ยังไม่ได้รับการรองรับสำหรับ int.to_bytes()

เมื่อจำนวนเต็มเป็นลบ 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

ยังไม่รองรับการลบ List ที่มี step != 1

วิธีแก้ไข: ใช้ loop แบบชัดเจนสำหรับการดำเนินการที่หายากนี้

โค้ดตัวอย่าง:

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 ที่ RHS ไม่ใช่ iterable

สาเหตุ: RHS จำกัดให้เป็น tuple หรือ list เท่านั้น

วิธีแก้ไข: ใช้ list(<iter>) บน RHS เพื่อแปลง iterable ให้เป็น 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

ยังไม่รองรับการเก็บค่า List ที่มี step != 1

วิธีแก้ไข: ใช้ loop แบบชัดเจนสำหรับการดำเนินการที่หายากนี้

โค้ดตัวอย่าง:

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 อาจกลายเป็น invalid ได้หากออบเจ็กต์เป้าหมายถูก resize

สาเหตุ: CPython จะป้องกันไม่ให้ออบเจ็กต์ bytearray หรือ io.bytesIO เปลี่ยนขนาดในขณะที่มีออบเจ็กต์ memoryview ที่อ้างอิงถึงมันอยู่ MicroPython กำหนดให้โปรแกรมเมอร์ตรวจสอบด้วยตนเองว่าออบเจ็กต์จะไม่ถูก resize ในขณะที่มี memoryview ใดๆ อ้างอิงถึงมัน

ในกรณีเลวร้ายที่สุด การ resize ออบเจ็กต์ที่เป็นเป้าหมายของ memoryview อาจทำให้ memoryview อ้างอิงถึงหน่วยความจำที่ถูกปลดปล่อยแล้วซึ่งไม่ถูกต้อง (บัก use-after-free) และทำให้ runtime ของ MicroPython เสียหาย

วิธีแก้ไข: อย่าเปลี่ยนขนาดของออบเจ็กต์ bytearray หรือ io.bytesIO ที่มี memoryview กำหนดให้

โค้ดตัวอย่าง:

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

ยังไม่รองรับ Attributes/subscr

โค้ดตัวอย่าง:

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(...) พร้อม keywords

วิธีแก้ไข: ป้อนรูปแบบ encoding โดยตรง เช่น 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 ได้รับการปรับให้เหมาะสมอย่างมากสำหรับการใช้หน่วยความจำ มีวิธีแก้ไขที่ง่ายดายให้ใช้ได้

วิธีแก้ไข: แทนที่จะใช้ s.ljust(10) ให้ใช้ "%-10s" % s แทนที่จะใช้ s.rjust(10) ให้ใช้ "% 10s" % s หรือใช้ "{:<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)

ยังไม่รองรับ Subscript ที่มี step != 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

ยังไม่รองรับการโหลด Tuple ที่มี step != 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