Skip to content

Commit d1bf0ee

Browse files
dlechdpgeorge
authored andcommitted
tests/cpydiff: Add diff for overriding __init__.
This adds a CPython diff that explains why calling `super().__init__()` is required in MicroPython when subclassing a native type (because `__new__` and `__init__` are not separate functions). Signed-off-by: David Lechner <[email protected]>
1 parent 9ca668f commit d1bf0ee

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
categories: Core,Classes
3+
description: When inheriting native types, calling a method in ``__init__(self, ...)`` before ``super().__init__()`` raises an ``AttributeError`` (or segfaults if ``MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG`` is not enabled).
4+
cause: MicroPython does not have separate ``__new__`` and ``__init__`` methods in native types.
5+
workaround: Call ``super().__init__()`` first.
6+
"""
7+
8+
9+
class L1(list):
10+
def __init__(self, a):
11+
self.append(a)
12+
13+
14+
try:
15+
L1(1)
16+
print("OK")
17+
except AttributeError:
18+
print("AttributeError")
19+
20+
21+
class L2(list):
22+
def __init__(self, a):
23+
super().__init__()
24+
self.append(a)
25+
26+
27+
try:
28+
L2(1)
29+
print("OK")
30+
except AttributeError:
31+
print("AttributeError")

0 commit comments

Comments
 (0)