Linguagem central¶
Generated Thu 18 Jun 2026 19:58:13 UTC
Classes¶
O método especial __del__ não está implementado para classes definidas pelo utilizador¶
Código de exemplo:
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__()
Código de exemplo:
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.
Código de exemplo:
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.
Código de exemplo:
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.
Código de exemplo:
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__'
|
A Ordem de Resolução de Métodos (MRO) não está em conformidade com o CPython¶
Causa: Ordem de resolução de métodos em profundidade primeiro não exaustiva
Solução: Evite hierarquias de classes complexas com herança múltipla e substituições de métodos complexas. Tenha em mente que muitas linguagens não suportam herança múltipla de todo.
Código de exemplo:
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)
|
A manipulação de nomes de membros privados de classes (name mangling) não está implementada¶
Causa: O compilador do MicroPython não implementa a manipulação de nomes para membros privados de classes.
Solução: Evite utilizar ou ter colisão com nomes globais, adicionando manualmente um prefixo único ao nome do membro privado da classe.
Código de exemplo:
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.
|
Ao herdar tipos nativos, chamar um método em __init__(self, ...) antes de super().__init__() gera um AttributeError (ou causa uma falha de segmentação se MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG não estiver ativado).¶
Causa: O MicroPython não tem métodos __new__ e __init__ separados em tipos nativos.
Solução: Chame super().__init__() primeiro.
Código de exemplo:
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
|
Ao herdar de múltiplas classes, super() só chama uma classe¶
Causa: Consulte A Ordem de Resolução de Métodos (MRO) não está em conformidade com o CPython
Solução: Consulte A Ordem de Resolução de Métodos (MRO) não está em conformidade com o CPython
Código de exemplo:
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__
|
Chamar a propriedade getter de super() numa subclasse devolverá um objeto property, não o valor¶
Código de exemplo:
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.
Código de exemplo:
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
|
Funções¶
As mensagens de erro para métodos podem apresentar contagens de argumentos inesperadas¶
Causa: O MicroPython conta «self» como um argumento.
Solução: Interprete as mensagens de erro tendo em conta a informação acima.
Código de exemplo:
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
|
Os objetos de função não têm o atributo __module__¶
Causa: O MicroPython é otimizado para reduzir o tamanho do código e o uso de RAM.
Solução: Utilize sys.modules[function.__globals__['__name__']] para módulos não incorporados.
Código de exemplo:
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__'
|
Atributos definidos pelo utilizador para funções não são suportados¶
Causa: O MicroPython é altamente otimizado para uso de memória.
Solução: Utilize um dicionário externo, por exemplo FUNC_X[f] = 0.
Código de exemplo:
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'
|
Generator¶
O gestor de contexto __exit__() não é chamado num gerador que não termina de executar¶
Código de exemplo:
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
|
Runtime¶
As variáveis locais não estão incluídas no resultado de locals()¶
Causa: O MicroPython não mantém um ambiente local simbólico; está otimizado para um array de slots. Assim, as variáveis locais não podem ser acedidas por nome.
Código de exemplo:
def test():
val = 2
print(locals())
test()
CPython output: |
MicroPython output: |
{'val': 2}
|
{'test': <function test at 0x7f186c605260>, '__name__': '__main__', '__file__': '<stdin>'}
|
O código a executar na função eval() não tem acesso a variáveis locais¶
Causa: O MicroPython não mantém um ambiente local simbólico; está otimizado para um array de slots. Assim, as variáveis locais não podem ser acedidas por nome. Na prática, eval(expr) no MicroPython é equivalente a eval(expr, globals(), globals()).
Código de exemplo:
val = 1
def test():
val = 2
print(val)
eval("print(val)")
test()
CPython output: |
MicroPython output: |
2
2
|
2
1
|
f-strings¶
As f-strings não suportam concatenação com literais adjacentes se os literais adjacentes contiverem chavetas¶
Causa: O MicroPython é otimizado para espaço de código.
Solução: Utilize o operador + entre strings literais quando não são ambas f-strings
Código de exemplo:
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
|
As f-strings não podem suportar expressões que requerem análise para resolver chavetas e parênteses aninhados desequilibrados¶
Causa: O MicroPython é otimizado para espaço de código.
Solução: Utilize sempre chavetas e parênteses equilibrados em expressões dentro de f-strings
Código de exemplo:
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
|
As f-strings não suportam conversões !a¶
Causa: O MicroPython não implementa ascii()
Solução: Nenhuma
Código de exemplo:
f"{'unicode text'!a}"
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 8
SyntaxError: invalid syntax
|
import¶
O atributo __path__ de um pacote tem um tipo diferente (string simples em vez de lista de strings) no MicroPython¶
Causa: O MicroPython não suporta pacotes de espaço de nomes distribuídos pelo sistema de ficheiros. Para além disso, o sistema de importação do MicroPython é altamente otimizado para uso mínimo de memória.
Solução: Os detalhes do tratamento de importações são inerentemente dependentes da implementação. Não dependa desses detalhes em aplicações portáteis.
Código de exemplo:
import modules
print(modules.__path__)
CPython output: |
MicroPython output: |
['/home/runner/work/openmv-doc/openmv-doc/micropython/tests/cpydiff/modules']
|
../tests/cpydiff/modules
|
O MicroPython não suporta pacotes de espaço de nomes distribuídos pelo sistema de ficheiros.¶
Causa: O sistema de importação do MicroPython é altamente otimizado para simplicidade, uso mínimo de memória e sobrecarga mínima de pesquisa no sistema de ficheiros.
Solução: Não instale módulos pertencentes ao mesmo pacote de espaço de nomes em diretórios diferentes. Para o MicroPython, recomenda-se ter no máximo 3 componentes no caminho de pesquisa de módulos: para a sua aplicação atual, por utilizador (gravável) e para todo o sistema (não gravável).
Código de exemplo:
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'
|