組み込み型¶
Generated Fri 19 Jun 2026 22:08:45 UTC
例外¶
StopIteration と OSError だけでなく、すべての例外が value および errno 属性を読み取ることができます。¶
原因: 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
|
例外チェーンは実装されていません¶
サンプルコード:
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__ のサポートはコンパイル時に除外することもでき、その場合は 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 派生型の 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 を収めるために出力長が 1 バイト多くなる場合があります。)
回避策: 負になる可能性のある整数値に 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 が解放済みの無効なメモリを参照し(use-after-free バグ)、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 はメモリ使用量に関して高度に最適化されています。簡単な回避策があります。
回避策: 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'
|
str.rsplit(None, n) のような rsplit の最初の引数に None を指定することは実装されていません¶
サンプルコード:
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
|