How to *not* create an instance
<p>I would like to avoid the creation of an instance if the arguments do not match the expected values.<br>
I.e. in short:  </p>

<pre><code>#!/usr/bin/env python3

class Test(object):
    def __init__(self, reallydoit = True):
        if reallydoit:
            self.done = True
        else:
            return None

make_me = Test()
make_me_not = Test(reallydoit=False)
</code></pre>

<p>I'd like <code>make_me_not</code> to be <code>None</code>, and I thought that <code>return None</code> could do it, but this variable is an instance of <code>Test</code> too:</p>

<pre><code>&gt;&gt;&gt; make_me
&lt;__main__.Test object at 0x7fd78c732390&gt;
&gt;&gt;&gt; make_me_not
&lt;__main__.Test object at 0x7fd78c732470&gt;
</code></pre>

<p>I'm sure there's a way to do this, but my Google-fu failed me so far.<br>
Thank you for any help.  </p>

<p><strong>EDIT:</strong> I would prefer this to be handled silently; the conditional should be interpreted as "Best not create this specific instance" instead of "You are using this class the wrong way". So yes, raising an error and then handling it is a possibility, but I'd prefer making less ruckus.</p>

<p>Just <a href="https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement" rel="nofollow">raise</a> an exception in the <a href="https://docs.python.org/3/reference/datamodel.html#object.__init__" rel="nofollow"><em>__init__</em></a> method:</p>

<pre><code>class Test(object):
    def __init__(self, reallydoit = True):
        if reallydoit:
            self.done = True
        else:
            raise ValueError('Not really doing it')
</code></pre>

<p>The other approach is to move your code to a <a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow"><em>__new__</em></a> method:</p>

<pre><code>class Test(object):
    def __new__(cls, reallydoit = True):
        if reallydoit:
            return object.__new__(cls)
        else:
            return None
</code></pre>

<p>Lastly, you could move the creation decision into a <a href="https://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow">factory function</a>:</p>

<pre><code>class Test(object):
    pass

def maybe_test(reallydoit=True):
    if reallydoit:
         return Test()
    return None
</code></pre>

python python-3.x