내장 타입¶
Generated Fri 19 Jun 2026 22:08:45 UTC
예외¶
StopIteration 및 OSError뿐만 아니라 모든 예외에 읽기 가능한 value 및 errno 속성이 있습니다.¶
원인: MicroPython은 코드 크기를 줄이도록 최적화되어 있습니다.
해결 방법: StopIteration 예외에는 value만, OSError 예외에는 errno만 사용하십시오. 다른 예외에서는 이 속성들을 사용하거나 의존하지 마십시오.
예제 코드:
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
|
예외 연쇄(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 루프 조건의 예외에 예상치 못한 줄 번호가 표시될 수 있음¶
원인: 조건 검사가 루프 본문의 끝에서 발생하도록 최적화되어 있으며, 해당 줄 번호가 보고됩니다.
예제 코드:
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¶
지원되지 않는 우변(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은 보다 일관된 구현을 지향하므로, 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
|
step != 1인 bytes 구독(subscription)이 구현되지 않음¶
원인: 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¶
딕셔너리 키 뷰(keys view)가 집합(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.¶
해결 방법: 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¶
step != 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:
|
우변(RHS)에 이터러블이 아닌 값을 사용한 리스트 슬라이스 저장이 구현되지 않음¶
원인: 우변(RHS)은 튜플 또는 리스트로 제한됩니다.
해결 방법: 우변(RHS)에 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
|
step != 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
|
속성/구독(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(…)이 구현되지 않음¶
해결 방법: 인코딩 형식을 직접 입력하십시오. 예: 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)
|
step != 1인 구독(subscript)이 아직 구현되지 않음¶
예제 코드:
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¶
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
|