summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Lechner <david@pybricks.com>2022-11-17 14:15:46 -0600
committerDamien George <damien@micropython.org>2024-07-25 12:01:43 +1000
commitd1bf0eeb0fb0c485da076075a15ffdfd5fb68303 (patch)
tree53973e585dbc3f03f3a1e795a238a0a55790a9e4
parent9ca668f881865958cbcc0e6341849a6133c4c7b4 (diff)
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 <david@pybricks.com>
-rw-r--r--tests/cpydiff/core_class_super_init.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/tests/cpydiff/core_class_super_init.py b/tests/cpydiff/core_class_super_init.py
new file mode 100644
index 000000000..1774f61dd
--- /dev/null
+++ b/tests/cpydiff/core_class_super_init.py
@@ -0,0 +1,31 @@
+"""
+categories: Core,Classes
+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).
+cause: MicroPython does not have separate ``__new__`` and ``__init__`` methods in native types.
+workaround: Call ``super().__init__()`` first.
+"""
+
+
+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")