Python del by class

Suppose we have a class in python:

class A(object): def __del__(self): print "Del!" 

__del__ causes the removal / garbage collection of any instance of A

Is it possible to do the same for a class? I would like to have some method called when the class itself is garbage collection, which I assume is executed in the output of the script.

Thanks in advance for any pointers!


Edit: As I expected, everyone is trying to drive me away from using this technique (I probably would have made such a comment myself :)), although the question still remains: is this possible?

I want the following: I have a class with a static member that needs to be cleared.

 class A(object): class Meta(type): def __new__(mcs, name, bases, attrs): attrs['conn'] = sqlite3.connect( DB_FILE ) return type.__new__(mcs, name, bases, attrs) __metaclass__ = Meta 

I would like A.conn.close() called, but shortly before the program closes - i.e. when I know there will be no more instances of A I know I can do this with atexit , but it seems very ugly.

+6
source share
1 answer

The problem is that classes contain circular references back to themselves - therefore, when they are deleted, they are not easy to assemble, therefore the __del__ odf metaclass method is not called.

I could call it using the Pypy Python implementation, but not using cpython - either 2.6 or 3.2. And even to cause this, I had to manually call the garbage collector - It is known that the Python environment when exiting the program is full of inconsistencies, and the capabilities of the __del__ method, called when there is sufficient internal information in the class, would exist to allow disabling sae, it would be very thin.

Here is my Pypy session where I called the class call ' __del__

  ~]$ pypy Python 2.5.2 (78826, Nov 29 2010, 00:18:05) [PyPy 1.4.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. And now for something completely different: ``sorry, I'll teach the cactus how to swim later'' >>>> import gc >>>> class Meta(type): .... def __del__(cls): .... print ("Arghh!!") .... >>>> class A(object): .... __metaclass__ = Meta .... >>>> del A >>>> gc.collect() Arghh!! 0 >>>> 
+4
source

Source: https://habr.com/ru/post/885578/


All Articles