핵심 언어

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)

비공개 클래스 멤버 이름 맹글링(name mangling)이 구현되지 않음

원인: 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.

네이티브 타입을 상속할 때, __init__(self, ...)에서 super().__init__() 이전에 메서드를 호출하면 AttributeError가 발생합니다(MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG가 활성화되지 않은 경우 segfault가 발생할 수 있음).

원인: 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()는 하나의 클래스만 호출함

원인: 메서드 결정 순서(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()의 getter 프로퍼티를 호출하면 값이 아닌 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-문자열이 인접 리터럴과의 연결을 지원하지 않음

원인: MicroPython은 코드 공간에 대해 최적화되어 있습니다.

해결 방법: 두 리터럴 문자열이 모두 f-문자열이 아닌 경우 + 연산자를 사용하십시오.

예제 코드:

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-문자열은 균형이 맞지 않는 중첩된 중괄호 및 대괄호를 파싱하여 해석해야 하는 표현식을 지원할 수 없음

원인: MicroPython은 코드 공간에 대해 최적화되어 있습니다.

해결 방법: f-문자열 내부의 표현식에는 항상 균형 잡힌 중괄호 및 대괄호를 사용하십시오.

예제 코드:

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-문자열은 !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 시스템은 최소 메모리 사용에 맞게 고도로 최적화되어 있습니다.

해결 방법: import 처리의 세부 사항은 본질적으로 구현에 따라 다릅니다. 이식 가능한 애플리케이션에서는 이러한 세부 사항에 의존하지 마십시오.

예제 코드:

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의 import 시스템은 단순성, 최소 메모리 사용, 최소 파일 시스템 검색 오버헤드에 맞게 고도로 최적화되어 있습니다.

해결 방법: 동일한 네임스페이스 패키지에 속하는 모듈을 서로 다른 디렉터리에 설치하지 마십시오. 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'