Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I abort object instance creation in Python?

Tags:

python

object

I want to set up a class that will abort during instance creation based on the value of the the argument passed to the class. I've tried a few things, one of them being raising an error in the __new__ method:

class a():
    def __new__(cls, x):
        if x == True:
            return cls
        else:
            raise ValueError

This is what I was hoping would happen:

>>obj1 = a(True)
>>obj2 = a(False)
ValueError Traceback (most recent call last)

obj1 exists but obj2 doesn't.

Any ideas?

like image 605
moorepants Avatar asked Oct 05 '10 21:10

moorepants


People also ask

How do you destroy an instance in Python?

Use the del keyword to delete class instance in Python. It's delete references to the instance, and once they are all gone, the object is reclaimed.

How do you empty an object in Python?

To delete an object in Python, we use the 'del' keyword. A when we try to refer to a deleted object, it raises NameError.

How do you delete a class object in Python?

The del keyword in python is primarily used to delete objects in Python. Since everything in python represents an object in one way or another, The del keyword can also be used to delete a list, slice a list, delete a dictionaries, remove key-value pairs from a dictionary, delete variables, etc.


2 Answers

When you override __new__, dont forget to call to super!

>>> class Test(object):
...     def __new__(cls, x):
...         if x:
...             return super(Test, cls).__new__(cls)
...         else:
...             raise ValueError
... 
>>> obj1 = Test(True)
>>> obj2 = Test(False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __new__
ValueError
>>> obj1
<__main__.Test object at 0xb7738b2c>
>>> obj2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'obj2' is not defined

Simply returning the class does nothing when it was your job to create an instance. This is what the super class's __new__ method does, so take advantage of it.

like image 102
aaronasterling Avatar answered Oct 02 '22 10:10

aaronasterling


Just raise an exception in the initializer:

class a(object):
    def __init__(self, x):
        if not x:
            raise Exception()
like image 38
Arlaharen Avatar answered Oct 02 '22 09:10

Arlaharen