Class destructor. Implementation error?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
ajvperth
Posts: 11
Joined: Fri Jul 08, 2022 12:21 am

Class destructor. Implementation error?

Post by ajvperth » Tue Jul 12, 2022 7:50 am

Hello,
possibly I found an implementation error in micropython?
on CPython this code:

Code: Select all

class Controller:

    def __init__(self):
        print('__init__()')
    
    def __del__(self):
        print('__del__()')
        
    def run(self):
        print('run()')

try:
    Controller().run()
except KeyboardInterrupt:
    print('\nTerminated, Ctrl-C pressed')
except BaseException as exc:
    print('\nUnhandled exception : ', type(exc), exc)
prints: __init__() then run() and __del__()
on micropython: __init__() and run().

_del__() is missing?? --> the destructor is not called?

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Class destructor. Implementation error?

Post by jimmo » Tue Jul 12, 2022 9:19 am

ajvperth wrote:
Tue Jul 12, 2022 7:50 am
_del__() is missing?? --> the destructor is not called?
This is a documented Micropython limitation:

https://docs.micropython.org/en/latest/ ... ed-classes

The additional overhead of tracking finalisation state for classes would be non-trivial. (We do this in a limited form for built-in types though)

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Class destructor. Implementation error?

Post by pythoncoder » Tue Jul 12, 2022 9:55 am

I've believe this is a limitation of CPython too - IIRC the destructor is not guaranteed to be called until you quit the interpreter. In a firmware "run forever" type application that equates to no guarantee at all.
Peter Hinch
Index to my micropython libraries.

ajvperth
Posts: 11
Joined: Fri Jul 08, 2022 12:21 am

Re: Class destructor. Implementation error?

Post by ajvperth » Tue Jul 12, 2022 11:14 am

Thanks, for pointing me to the page with core language limitations.
I did read it but did not realize the consequences.

Post Reply