Roberto Roberto - 1 month ago 7
Python Question

How to *not* create an instance

I would like to avoid the creation of an instance if the arguments do not match the expected values.

I.e. in short:

#!/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)


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

>>> make_me
<__main__.Test object at 0x7fd78c732390>
>>> make_me_not
<__main__.Test object at 0x7fd78c732470>


I'm sure there's a way to do this, but my Google-fu failed me so far.

Thank you for any help.

EDIT: 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.

Answer

Just raise an exception in the __init__ method:

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

The other approach is to move your code to a __new__ method:

class Test(object):
    def __new__(cls, reallydoit = True):
        if reallydoit:
            return object.__new__(cls)
        else:
            return None

Lastly, you could move the creation decision into a factory function:

class Test(object):
    pass

def maybe_test(reallydoit=True):
    if reallydoit:
         return Test()
    return None
Comments