There is a class Foo :

 class Foo: def __init__(self, data = None): if data == None: self.__del__() def __del__(self): print('Error') f = Foo() # Error print(f) # <__main__.Foo object at 0x7fc1210de1d0> 

I have this problem:

If I create an instance of a class, I need to check if the data argument is passed. If not, class creation needs to be canceled. I call the __del__ method from the __init__ method, but the instance remains in memory, this can be checked using print(f) . Already once I did it, maybe I forgot something, but I don’t understand at all: how to fix and what to google?

  • It is impossible to delete an already created class instance by yourself. The __del__ function is a regular function (well, or a method, if you like) and it means nothing (in some implementations of Python, it is not used at all). The only thing that can be done is to throw an exception into __init__ and hope that one day a garbage collector will come after the created instance of the class and delete it (and in some implementations it may not come) - andreymal
  • @andreymal, something is doubtful to me that an exception in __init__ may affect something ... As I recall, by the time __init__ is called, an instance has already been created. Perhaps manipulating __new__ might help. - Xander
  • @ Alexander yes, that's why I wrote about the garbage collector. __new__ possible, but I worked very little with him, I don’t know - andreymal

1 answer 1

IMHO, you need not to delete an already created instance, but simply not to create it. The creation is controlled by the __new__ method, which is triggered before __init__ , and receives the same arguments as input. The __new__ method should create and return a fresh instance of the class. Accordingly, you can try to override this method so that in certain cases it does not create anything.

 class Foo: def __new__(cls, data=None): if data is None: print('Error') return None else: return super().__new__(cls) f1 = Foo() # Error print(f1) # None f2 = Foo('some data') print(f2) # <__main__.Foo object at 0x7f3e5fb22a90> 
  • That's what I need. Thank. - Don2Quixote