このドキュメンテーションは、MicroPython の最新開発ブランチのためのものです。 リリースバージョンでは利用できない機能に言及することがあります。

特定のリリースのドキュメントをお探しの場合は、左側のドロップダウンメニューを使って、 望みのバージョンを選択します。

組込み型

Generated Wed 07 Feb 2024 12:13:19 UTC

例外

すべての例外には可視な valueerrno の属性がある。 StopIterationOSError に限らない。

原因: MicroPython はコードサイズを削減するよう最適化されています。

回避策: StopIteration 例外では value のみを使い、 OSError 例外では errno のみを使います。他の例外では、これらの属性を使ったり依存したりしないでください。

サンプルコード:

e = Exception(1)
print(e.value)
print(e.errno)

CPy 出力:

uPy 出力:

Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
AttributeError: 'Exception' object has no attribute 'value'
1
1

例外チェーンは実装されていない

サンプルコード:

try:
    raise TypeError
except TypeError:
    raise ValueError

CPy 出力:

uPy 出力:

Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
TypeError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 10, in <module>
ValueError
Traceback (most recent call last):
  File "<stdin>", line 10, in <module>
ValueError:

組込み例外のユーザ定義属性はサポートされない

原因: MicroPython はメモリ使用量について高度に最適化しています。

回避策: ユーザ定義の例外サブクラスを使ってください。

サンプルコード:

e = Exception()
e.x = 0
print(e.x)

CPy 出力:

uPy 出力:

0
Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
AttributeError: 'Exception' object has no attribute 'x'

while ループ条件での例外は予期しない行番号になる

原因: 条件チェックはループ本体の最後で実行されるように最適化されているので、その行番号が報告されます。

サンプルコード:

l = ["-foo", "-bar"]

i = 0
while l[i][0] == "-":
    print("iter")
    i += 1

CPy 出力:

uPy 出力:

iter
iter
Traceback (most recent call last):
  File "<stdin>", line 10, in <module>
IndexError: list index out of range
iter
iter
Traceback (most recent call last):
  File "<stdin>", line 12, 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()

CPy 出力:

uPy 出力:

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__'

bytearray

配列スライスへの代入はサポートされない

サンプルコード:

b = bytearray(4)
b[0:1] = [1, 2]
print(b)

CPy 出力:

uPy 出力:

bytearray(b'\x01\x02\x00\x00\x00')
Traceback (most recent call last):
  File "<stdin>", line 8, 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))

CPy 出力:

uPy 出力:

Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
AttributeError: 'bytes' object has no attribute 'format'
b'1'

bytes() のキーワード引数は未実装

回避策: エンコーディングは位置パラメータで渡してください。たとえば print(bytes('abc', 'utf-8')) のようにします。

サンプルコード:

print(bytes("abc", encoding="utf8"))

CPy 出力:

uPy 出力:

b'abc'
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NotImplementedError: keyword argument(s) not implemented - use normal args instead

スライスのステップが1以外は未実装

原因: MicroPython はメモリ使用量について高度に最適化しています。

回避策: このまれな操作には明示的なループを使ってください。

サンプルコード:

print(b"123"[0:3:2])

CPy 出力:

uPy 出力:

b'13'
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported

dict

辞書キーのビューが集合として動作しない。

原因: 未実装。

回避策: 集合操作を使う前に、キーを明示的に集合に変換してください。

サンプルコード:

print({1: 2, 3: 4}.keys() & {1})

CPy 出力:

uPy 出力:

{1}
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
TypeError: unsupported types for __and__: 'dict_view', 'set'

float

uPy では数学演算の際にオブジェクトの暗黙の変換が可能ですが、CPythonではできない。

回避策: CPythonとの互換性のために、オブジェクトはfloat(obj)でラップすべき。

サンプルコード:

class Test:
    def __float__(self):
        return 0.5


print(2.0 * Test())

CPy 出力:

uPy 出力:

Traceback (most recent call last):
  File "<stdin>", line 14, in <module>
TypeError: unsupported operand type(s) for *: 'float' and 'Test'
1.0

uPy と CPython の出力フォーマットが異なることがある

サンプルコード:

print("%.1g" % -9.9)

CPy 出力:

uPy 出力:

-1e+01
-10

int

bit_length メソッドは存在しない。

原因: bit_length メソッドは未実装。

回避策: MicroPython ではこのメソッドを利用しない。

サンプルコード:

x = 255
print("{} is {} bits long.".format(x, x.bit_length()))

CPy 出力:

uPy 出力:

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)

CPy 出力:

uPy 出力:

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'

list

ステップが 1 以外のリスト要素の削除は未実装

回避策: このまれな操作には明示的なループを使ってください。

サンプルコード:

l = [1, 2, 3, 4]
del l[0:4:2]
print(l)

CPy 出力:

uPy 出力:

[2, 4]
Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
NotImplementedError:

リストのスライスへのイテレーティブの代入は未実装

原因: 右辺はタプルかリストに制限されています。

回避策: イテレータブルをリストに変換するよう、右辺で list(<iter>) を使ってください。

サンプルコード:

l = [10, 20]
l[0:1] = range(4)
print(l)

CPy 出力:

uPy 出力:

[0, 1, 2, 3, 20]
Traceback (most recent call last):
  File "<stdin>", line 8, 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)

CPy 出力:

uPy 出力:

[5, 2, 6, 4]
Traceback (most recent call last):
  File "<stdin>", line 8, in <module>
NotImplementedError:

str

str.endswith(s, start) のような開始/終了インデックスは未実装

サンプルコード:

print("abc".endswith("c", 1))

CPy 出力:

uPy 出力:

True
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NotImplementedError: start/end indices

属性置換は未実装

サンプルコード:

print("{a[0]}".format(a=[1, 2]))

CPy 出力:

uPy 出力:

1
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NotImplementedError: attributes not supported

str(...) のキーワード引数は未実装

回避策: エンコーディングは位置パラメータで指定してください。たとえば print(str(b'abc', 'utf-8')) のようにします。

サンプルコード:

print(str(b"abc", encoding="utf8"))

CPy 出力:

uPy 出力:

abc
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NotImplementedError: keyword argument(s) not implemented - use normal args instead

str.ljust() と str.rjust() は未実装

原因: MicroPython はメモリ使用量について高度に最適化しています。これは簡単に回避できます。

回避策: s.ljust(10) の代わりに "%-10s" % ss.rjust(10) の代わりに "% 10s" % s を使ってください。あるいは "{:<10}".format(s)"{:>10}".format(s) を使ってください。

サンプルコード:

print("abc".ljust(10))

CPy 出力:

uPy 出力:

abc
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
AttributeError: 'str' object has no attribute 'ljust'

str.rsplit(None, n) のように rsplit の第1引数を None にするのは未実装

サンプルコード:

print("a a a".rsplit(None, 1))

CPy 出力:

uPy 出力:

['a a', 'a']
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NotImplementedError: rsplit(None,n)

ステップが 1 でないスライスは未実装

サンプルコード:

print("abcdefghi"[0:9:2])

CPy 出力:

uPy 出力:

acegi
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported

tuple

ステップが 1 でないタプルのスライスは未実装

サンプルコード:

print((1, 2, 3, 4)[0:4:2])

CPy 出力:

uPy 出力:

(1, 3)
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
NotImplementedError: only slices with step=1 (aka None) are supported