Tipos incorporados¶
Generated Thu 18 Jun 2026 19:58:13 UTC
Exception¶
Todas as exceções têm os atributos legíveis value e errno, não apenas StopIteration e OSError.¶
Causa: O MicroPython é otimizado para reduzir o tamanho do código.
Solução: Utilize value apenas em exceções StopIteration e errno apenas em exceções OSError. Não utilize nem dependa desses atributos noutras exceções.
Código de exemplo:
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
|
Encadeamento de exceções não implementado¶
Código de exemplo:
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:
|
Atributos definidos pelo utilizador para exceções incorporadas não são suportados¶
Causa: O MicroPython é altamente otimizado para uso de memória.
Solução: Utilize subclasses de exceções definidas pelo utilizador.
Código de exemplo:
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'
|
A exceção numa condição de ciclo while pode ter um número de linha inesperado¶
Causa: As verificações de condição são otimizadas para ocorrer no fim do corpo do ciclo, e é esse número de linha que é reportado.
Código de exemplo:
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
|
O método Exception.__init__ não existe.¶
Causa: A criação de subclasses de classes nativas não é totalmente suportada no MicroPython.
Solução: Chame usando super() em vez disso:
class A(Exception):
def __init__(self):
super().__init__()
Código de exemplo:
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.
Código de exemplo:
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¶
Atribuição de fatia de array com RHS não suportado¶
Código de exemplo:
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¶
Os objetos bytes suportam o método .format()¶
Causa: O MicroPython esforça-se por ser uma implementação mais regular, pelo que, se tanto str como bytes suportam __mod__() (o operador %), faz sentido suportar format() para ambos também. O suporte para __mod__ também pode ser excluído da compilação, ficando apenas format() para formatação de bytes.
Solução: Se pretende compatibilidade com CPython, não utilize .format() em objetos bytes.
Código de exemplo:
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() com palavras-chave não implementado¶
Solução: Passe a codificação como parâmetro posicional, por exemplo print(bytes('abc', 'utf-8'))
Código de exemplo:
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
|
Subscrição de bytes com passo != 1 não implementado¶
Causa: O MicroPython é altamente otimizado para uso de memória.
Solução: Utilize um ciclo explícito para esta operação muito rara.
Código de exemplo:
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¶
Causa: O MicroPython é altamente otimizado para uso de memória.
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.
Código de exemplo:
try:
print(complex("1 1j"))
except ValueError:
print("ValueError")
CPython output: |
MicroPython output: |
ValueError
|
(1+1j)
|
dict¶
A vista das chaves do dicionário não se comporta como um conjunto.¶
Causa: Não implementado.
Solução: Converta explicitamente as chaves para um conjunto antes de utilizar operações de conjunto.
Código de exemplo:
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.¶
Solução: Os objetos devem ser encapsulados em float(obj) para compatibilidade com CPython.
Código de exemplo:
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¶
O método bit_length não existe.¶
Causa: O método bit_length não está implementado.
Solução: Evite utilizar este método no MicroPython.
Código de exemplo:
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'
|
Não está disponível conversão int para tipos derivados de int¶
Solução: Evite criar subclasses de tipos incorporados a menos que seja mesmo necessário. Prefira https://en.wikipedia.org/wiki/Composition_over_inheritance .
Código de exemplo:
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'
|
O método to_bytes não implementa o parâmetro signed.¶
Causa: O parâmetro exclusivo de palavra-chave signed não está implementado para int.to_bytes().
Quando o inteiro é negativo, o MicroPython comporta-se da mesma forma que o CPython int.to_bytes(..., signed=True)
Quando o inteiro é não negativo, o MicroPython comporta-se da mesma forma que o CPython int.to_bytes(..., signed=False).
(A diferença é subtil, mas no CPython um inteiro positivo convertido com signed=True pode necessitar de mais um byte no comprimento da saída, de modo a caber o bit de sinal 0.)
Solução: Tenha cuidado ao chamar to_bytes() num valor inteiro que pode ser negativo.
Código de exemplo:
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¶
Eliminação de lista com passo != 1 não implementado¶
Solução: Utilize um ciclo explícito para esta operação rara.
Código de exemplo:
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:
|
Armazenamento de fatia de lista com valor não iterável no RHS não está implementado¶
Causa: O RHS está restrito a ser um tuplo ou lista
Solução: Utilize list(<iter>) no RHS para converter o iterável numa lista
Código de exemplo:
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
|
Armazenamento de lista com passo != 1 não implementado¶
Solução: Utilize um ciclo explícito para esta operação rara.
Código de exemplo:
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¶
A memoryview pode tornar-se inválida se o seu alvo for redimensionado¶
Causa: O CPython impede que um objeto bytearray ou io.bytesIO altere o tamanho enquanto existe um objeto memoryview que o referencia. O MicroPython exige que o programador garanta manualmente que um objeto não é redimensionado enquanto qualquer memoryview o referencia.
No pior cenário, redimensionar um objeto que é alvo de uma memoryview pode fazer com que a(s) memoryview(s) referencie(m) memória liberada inválida (um bug use-after-free) e corrompa o ambiente de execução do MicroPython.
Solução: Não altere o tamanho de nenhum objeto bytearray ou io.bytesIO que tenha uma memoryview atribuída a ele.
Código de exemplo:
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
Código de exemplo:
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.
Código de exemplo:
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.
Código de exemplo:
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
|
Atributos/subscrição não implementados¶
Código de exemplo:
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(…) com palavras-chave não implementado¶
Solução: Introduza o formato de codificação diretamente. Por exemplo print(bytes('abc', 'utf-8'))
Código de exemplo:
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() e str.rjust() não implementados¶
Causa: O MicroPython é altamente otimizado para uso de memória. Existem soluções alternativas fáceis.
Solução: Em vez de s.ljust(10) utilize "%-10s" % s, em vez de s.rjust(10) utilize "% 10s" % s. Em alternativa, "{:<10}".format(s) ou "{:>10}".format(s).
Código de exemplo:
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'
|
None como primeiro argumento para rsplit como str.rsplit(None, n) não implementado¶
Código de exemplo:
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)
|
Subscrição com passo != 1 ainda não implementado¶
Código de exemplo:
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¶
Carregamento de tuplo com passo != 1 não implementado¶
Código de exemplo:
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
|