Cancel instance create

Fredrik Lundh fredrik at pythonware.com
Sat Sep 6 07:11:04 EDT 2008


Aigars Aigars wrote:

> I want MyClass to perform some tests and if them fail, I do not want 
> instance to be created.
> 
> But in code I wrote instance is created and also has parameters, that it 
> should not have in case of tests failure.
> 
> Is there a way to perform tests in MyClass.__init__ and set instance to 
> None without any parameters?

if you want construction to fail, raise an exception.

     ...

     def __init__(self):
         self.param = "spam"
         Test = False
         if Test: # please don't use explicit tests for truth
             print "Creating instance..."
         else:
             raise ValueError("some condition failed")

(pick an exception class that matches the actual error, or create your 
own class if necessary)

</F>




More information about the Python-list mailing list