Files
micropython/tests/misc/cexample_subclass.py
Laurens Valk 9ca668f881 py/objtype: Avoid crash on calling members of uninitialized native type.
When subclassing a native type, calling native members in `__init__` before
`super().__init__()` has been called could cause a crash.  In this
situation, `self` in `mp_convert_member_lookup` is the
`native_base_init_wrapper_obj`.  The check added in this commit ensures
that an `AttributeError` is raised before this happens, which is consistent
with other failed lookups.

Also fix a typo in a related comment.

Signed-off-by: Laurens Valk <laurens@pybricks.com>
2024-07-25 12:01:43 +10:00

38 lines
859 B
Python

# test subclassing custom native class
try:
from cexample import AdvancedTimer
except ImportError:
print("SKIP")
raise SystemExit
class SubTimer(AdvancedTimer):
def __init__(self):
# At this point, self does not yet represent a AdvancedTimer instance.
print(self)
# So lookups via type.attr handler will fail.
try:
self.seconds
except AttributeError:
print("AttributeError")
# Also applies to builtin methods.
try:
self.time()
except AttributeError:
print("AttributeError")
# Initialize base class.
super().__init__(self)
# Now you can access methods and attributes normally.
self.time()
print(self.seconds)
self.seconds = 123
print(self.seconds)
watch = SubTimer()