コア言語¶
Generated Fri 19 Jun 2026 22:08:45 UTC
クラス¶
ユーザー定義クラスの特殊メソッド __del__ は実装されていません¶
サンプルコード:
import gc
class Foo:
def __del__(self):
print("__del__")
f = Foo()
del f
gc.collect()
CPython output: | MicroPython output: |
__del__
|
__init_subclass__ isn't automatically called.¶
Cause: MicroPython does not currently implement PEP 487.
Workaround: Manually call __init_subclass__ after class creation if needed. e.g.:
class A(Base):
pass
A.__init_subclass__()
サンプルコード:
class Base:
@classmethod
def __init_subclass__(cls):
print(f"Base.__init_subclass__({cls.__name__})")
class A(Base):
pass
CPython output: | MicroPython output: |
Base.__init_subclass__(A)
|
__init_subclass__ isn't an implicit classmethod.¶
Cause: MicroPython does not currently implement PEP 487. __init_subclass__ is not currently in the list of special-cased class/static methods.
Workaround: Decorate declarations of __init_subclass__ with @classmethod.
サンプルコード:
def regularize_spelling(text, prefix="bound_"):
# for regularizing across the CPython "method" vs MicroPython "bound_method" spelling for the type of a bound classmethod
if text.startswith(prefix):
return text[len(prefix) :]
return text
class A:
def __init_subclass__(cls):
pass
@classmethod
def manual_decorated(cls):
pass
a = type(A.__init_subclass__).__name__
b = type(A.manual_decorated).__name__
print(regularize_spelling(a))
print(regularize_spelling(b))
if a != b:
print("FAIL")
CPython output: | MicroPython output: |
method
method
| function
method
FAIL
|
MicroPython doesn't support parameterized __init_subclass__ class customization.¶
Cause: MicroPython does not currently implement PEP 487. The MicroPython syntax tree does not include a kwargs node after the class inheritance list.
Workaround: Use class variables or another mechanism to specify base-class customizations.
サンプルコード:
class Base:
@classmethod
def __init_subclass__(cls, arg=None, **kwargs):
cls.init_subclass_was_called = True
print(f"Base.__init_subclass__({cls.__name__}, {arg=!r}, {kwargs=!r})")
class A(Base, arg="arg"):
pass
# Regularize across MicroPython not automatically calling __init_subclass__ either.
if not getattr(A, "init_subclass_was_called", False):
A.__init_subclass__()
CPython output: | MicroPython output: |
Base.__init_subclass__(A, arg='arg', kwargs={})
| Traceback (most recent call last):
File "<stdin>", line 16, in <module>
TypeError: function doesn't take keyword arguments
|
__init_subclass__ can't be defined a cooperatively-recursive way.¶
Cause: MicroPython does not currently implement PEP 487. The base object type does not have an __init_subclass__ implementation.
Workaround: Omit the recursive __init_subclass__ call unless it's known that the grandparent also defines it.
サンプルコード:
class Base:
@classmethod
def __init_subclass__(cls, **kwargs):
cls.init_subclass_was_called = True
super().__init_subclass__(**kwargs)
class A(Base):
pass
# Regularize across MicroPython not automatically calling __init_subclass__ either.
if not getattr(A, "init_subclass_was_called", False):
A.__init_subclass__()
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 22, in <module>
File "<stdin>", line 13, in __init_subclass__
AttributeError: 'super' object has no attribute '__init_subclass__'
|
メソッド解決順序 (MRO) が CPython に準拠していません¶
原因: 深さ優先の非網羅的なメソッド解決順序
回避策: 多重継承や複雑なメソッドオーバーライドを伴う複雑なクラス階層を避けてください。多くの言語は多重継承をまったくサポートしていないことを念頭に置いてください。
サンプルコード:
class Foo:
def __str__(self):
return "Foo"
class C(tuple, Foo):
pass
t = C((1, 2, 3))
print(t)
CPython output: | MicroPython output: |
Foo
| (1, 2, 3)
|
プライベートクラスメンバーの名前マングリングは実装されていません¶
原因: MicroPython コンパイラはプライベートクラスメンバーの名前マングリングを実装していません。
回避策: グローバル名との衝突を避けるため、プライベートクラスメンバー名に手動で一意のプレフィックスを付けてください。
サンプルコード:
def __print_string(string):
print(string)
class Foo:
def __init__(self, string):
self.string = string
def do_print(self):
__print_string(self.string)
example_string = "Example String to print."
class_item = Foo(example_string)
print(class_item.string)
class_item.do_print()
CPython output: | MicroPython output: |
Example String to print.
Traceback (most recent call last):
File "<stdin>", line 26, in <module>
File "<stdin>", line 18, in do_print
NameError: name '_Foo__print_string' is not defined. Did you mean: '__print_string'?
| Example String to print.
Example String to print.
|
ネイティブ型を継承する場合、super().__init__() より前に __init__(self, ...) 内でメソッドを呼び出すと AttributeError が発生します(MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG が有効でない場合はセグメンテーション違反になります)。¶
原因: MicroPython のネイティブ型には、__new__ と __init__ のメソッドが分離されていません。
回避策: 最初に super().__init__() を呼び出してください。
サンプルコード:
class L1(list):
def __init__(self, a):
self.append(a)
try:
L1(1)
print("OK")
except AttributeError:
print("AttributeError")
class L2(list):
def __init__(self, a):
super().__init__()
self.append(a)
try:
L2(1)
print("OK")
except AttributeError:
print("AttributeError")
CPython output: | MicroPython output: |
OK
OK
| AttributeError
OK
|
複数のクラスを継承する場合、super() は 1 つのクラスしか呼び出しません¶
原因: メソッド解決順序 (MRO) が CPython に準拠していません を参照してください
回避策: メソッド解決順序 (MRO) が CPython に準拠していません を参照してください
サンプルコード:
class A:
def __init__(self):
print("A.__init__")
class B(A):
def __init__(self):
print("B.__init__")
super().__init__()
class C(A):
def __init__(self):
print("C.__init__")
super().__init__()
class D(B, C):
def __init__(self):
print("D.__init__")
super().__init__()
D()
CPython output: | MicroPython output: |
D.__init__
B.__init__
C.__init__
A.__init__
| D.__init__
B.__init__
A.__init__
|
サブクラスで super() のゲッタープロパティを呼び出すと、値ではなく property オブジェクトが返されます¶
サンプルコード:
class A:
@property
def p(self):
return {"a": 10}
class AA(A):
@property
def p(self):
return super().p
a = AA()
print(a.p)
CPython output: | MicroPython output: |
{'a': 10}
| <property>
|
Exceptions¶
Throwing a derived exception class instance in its __init__ without first calling super().__init__ is a TypeError¶
Cause: In MicroPython, an object is incompletely constructed if it does not call its superclass init function or return normally from its __init__. This prevents its usage in some circumstances.
Workaround: Call the superclass __init__ method before raising the exception.
サンプルコード:
class C(Exception):
def __init__(self):
raise self
class C1(Exception):
def __init__(self):
super().__init__()
raise self
try:
C()
except Exception as e:
print(type(e).__name__)
try:
C1()
except Exception as e:
print(type(e).__name__)
CPython output: | MicroPython output: |
C
C1
| TypeError
C1
|
関数¶
メソッドのエラーメッセージに予期しない引数の数が表示される場合があります¶
原因: MicroPython は "self" を引数としてカウントします。
回避策: 上記の情報を念頭に置いてエラーメッセージを解釈してください。
サンプルコード:
try:
[].append()
except Exception as e:
print(e)
CPython output: | MicroPython output: |
list.append() takes exactly one argument (0 given)
| function takes 2 positional arguments but 1 were given
|
関数オブジェクトは __module__ 属性を持ちません¶
原因: MicroPython はコードサイズと RAM 使用量の削減のために最適化されています。
回避策: 組み込みモジュール以外のモジュールには sys.modules[function.__globals__['__name__']] を使用してください。
サンプルコード:
def f():
pass
print(f.__module__)
CPython output: | MicroPython output: |
__main__
| Traceback (most recent call last):
File "<stdin>", line 13, in <module>
AttributeError: 'function' object has no attribute '__module__'
|
関数のユーザー定義属性はサポートされていません¶
原因: MicroPython はメモリ使用量に関して高度に最適化されています。
回避策: 外部辞書を使用してください。例: FUNC_X[f] = 0
サンプルコード:
def f():
pass
f.x = 0
print(f.x)
CPython output: | MicroPython output: |
0
| Traceback (most recent call last):
File "<stdin>", line 13, in <module>
AttributeError: 'function' object has no attribute 'x'
|
ジェネレーター¶
最後まで実行されないジェネレーターでは、コンテキストマネージャーの __exit__() が呼び出されません¶
サンプルコード:
class foo(object):
def __enter__(self):
print("Enter")
def __exit__(self, *args):
print("Exit")
def bar(x):
with foo():
while True:
x += 1
yield x
def func():
g = bar(0)
for _ in range(3):
print(next(g))
func()
CPython output: | MicroPython output: |
Enter
1
2
3
Exit
| Enter
1
2
3
|
ランタイム¶
ローカル変数は locals() の結果に含まれません¶
原因: MicroPython はシンボリックなローカル環境を維持せず、スロットの配列に最適化されています。そのため、ローカル変数に名前でアクセスすることができません。
サンプルコード:
def test():
val = 2
print(locals())
test()
CPython output: | MicroPython output: |
{'val': 2}
| {'test': <function test at 0x7f5d74c05260>, '__name__': '__main__', '__file__': '<stdin>'}
|
eval() 関数内で実行されるコードはローカル変数にアクセスできません¶
原因: MicroPython はシンボリックなローカル環境を維持せず、スロットの配列に最適化されています。そのため、ローカル変数に名前でアクセスすることができません。実質的に、MicroPython における eval(expr) は eval(expr, globals(), globals()) と等価です。
サンプルコード:
val = 1
def test():
val = 2
print(val)
eval("print(val)")
test()
CPython output: | MicroPython output: |
2
2
| 2
1
|
f-strings¶
隣接するリテラルに波括弧が含まれている場合、f-string は隣接するリテラルとの連結をサポートしません¶
原因: MicroPython はコード領域を節約するよう最適化されています。
回避策: どちらも f-string でない場合は、リテラル文字列間で + 演算子を使用してください
サンプルコード:
x, y = 1, 2
print("aa" f"{x}") # works
print(f"{x}" "ab") # works
print("a{}a" f"{x}") # fails
print(f"{x}" "a{}b") # fails
CPython output: | MicroPython output: |
aa1
1ab
a{}a1
1a{}b
| aa1
1ab
Traceback (most recent call last):
File "<stdin>", line 12, in <module>
IndexError: tuple index out of range
|
f-string は、バランスの取れていないネストされた波括弧や角括弧を解決するための解析が必要な式をサポートできません¶
原因: MicroPython はコード領域を節約するよう最適化されています。
回避策: f-string 内の式では常にバランスの取れた波括弧と角括弧を使用してください
サンプルコード:
print(f"{'hello { world'}")
print(f"{'hello ] world'}")
CPython output: | MicroPython output: |
hello { world
hello ] world
| Traceback (most recent call last):
File "<stdin>", line 9
SyntaxError: invalid syntax
|
f-string は !a 変換をサポートしません¶
原因: MicroPython は ascii() を実装していません
回避策: なし
サンプルコード:
f"{'unicode text'!a}"
CPython output: | MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 8
SyntaxError: invalid syntax
|
import¶
MicroPython では、パッケージの __path__ 属性の型が異なります(文字列リストの代わりに単一の文字列)¶
原因: MicroPython はファイルシステムをまたがる名前空間パッケージをサポートしていません。さらに、MicroPython のインポートシステムは最小メモリ使用量に向けて高度に最適化されています。
回避策: インポート処理の詳細は本質的に実装に依存します。ポータブルなアプリケーションではこのような詳細に依存しないでください。
サンプルコード:
import modules
print(modules.__path__)
CPython output: | MicroPython output: |
['/home/runner/work/openmv-doc/openmv-doc/micropython/tests/cpydiff/modules']
| ../tests/cpydiff/modules
|
MicroPython はファイルシステムをまたがる名前空間パッケージをサポートしていません。¶
原因: MicroPython のインポートシステムはシンプルさ、最小メモリ使用量、最小ファイルシステム検索オーバーヘッドに向けて高度に最適化されています。
回避策: 同じ名前空間パッケージに属するモジュールを異なるディレクトリにインストールしないでください。MicroPython では、モジュール検索パスを最大 3 つのコンポーネント(現在のアプリケーション用、ユーザーごと(書き込み可能)、システム全体(書き込み不可))にすることが推奨されます。
サンプルコード:
import sys
sys.path.append(sys.path[1] + "/modules")
sys.path.append(sys.path[1] + "/modules2")
import subpkg.foo
import subpkg.bar
print("Two modules of a split namespace package imported")
CPython output: | MicroPython output: |
Two modules of a split namespace package imported
| Traceback (most recent call last):
File "<stdin>", line 14, in <module>
ImportError: no module named 'subpkg.bar'
|