Micropython does not call finalisers for user defined classes. Although alternatives are usually preferable, there are situations were finalisers are useful.
To enable finalisers with user define classes, I created a class FinaliserProxy in C. User defined classes derive from this class as follows:
Code: Select all
def cb(self):
print("finaliser for", self.desc, "called")
class FP(FinaliserProxy):
def __init__(self, cb, desc):
self.desc = desc
super().__init__(cb, self)
f = FP(cb, "my custom class with finalizer")
# ... use f, then
# del f or f = None
Implementation detail: the constructor of FinaliserProxy takes self of the derived class as an argument. The reason is that when the C finaliser is called it always receives FinaliserProxy, not the derived class as self. Perhaps there is a better way to do this?
I welcome feedback about this solution including potential pitfalls (I am aware that the object is never be collected if the gc does not run).