user3557216
user3557216

Reputation: 269

How can I have python notify if an objected is deleted before the script finishes running?

Basically I have some objects that I want to make available at global level, and I want to be notified if the user accidentally overwrites any of them, because they have very common variable names (this is necessary, and I cannot get around it).

So, for instance, if the user does b=2, and later the garbage collector does a sweep, I want to be notified that b was destroyed. However, if this happens at the end of the script, when everything else is being garbage collected, that should be silent. This is why simply implementing a __del__ method is not good enough.

I'm delving into the weakref module but it doesn't seem to be what I need.

Upvotes: 1

Views: 337

Answers (1)

nneonneo
nneonneo

Reputation: 179392

If you're executing external "untrusted" code via exec or eval, you can pass in a custom globals object that can tell you if something gets overwritten or deleted. You can even arrange to forbid certain kinds of modifications.

As a simple example:

class readonly_dict(dict):
    def __setitem__(self, key, value):
        raise NotImplementedError

exec "print x; x = 3" in readonly_dict(x = 10)

This prints 10, then throws a NotImplementedError when the user code tries to change x. You can override __delitem__ and __setitem__ to suit your needs.


As for suppressing output from __del__ at exit: you can use the register function from the built-in atexit module to register a shutdown hook that runs before destructors, and have it set a flag that silences __del__.

Upvotes: 4

Related Questions