what to do when instance of class fails to initialize ?

John J. Lee jjl at pobox.com
Wed Aug 20 15:26:35 EDT 2003


Tom Van den Brandt <guineapig at pi.be> writes:

> If I have an __init__ for a class and the initialisation can't go through
> (example: missing or wrong arguments), how do I return an error to the
> caller (from main() function)?  When I do a return statement in the
> __init__ it says __init__ should return None...  I can stop the flow with
> raise 'BlahBlah'. But then the program exits.
> 
> What is the nice way to do this ? 

Raise an exception.  But do it with a real exception, *never* use
string exceptions (if they aren't officially deprecated, they
certainly soon will be).


class BadRhubarbError(Exception): pass

class foo:
    def __init__(self, i, rhubarb=None):
        self._i = int(i)  # raises TypeError on failure
        if rhubarb is not None:
            rhubarb = "rhubarb"  # default
        if not good_rhubarb(rhubarb):
            raise BadRhubarbError()  # explicitly raised exception
        self.rhubarb = rhubarb

    def blah():
        ...

def use_a_foo():
    try:
        f = foo()
    except TypeError:
        return None  # or whatever
    except BadRhubarbError:
        sys.exit("bad rhubarb!!")
    else:
        return f.blah()


Remember exceptions propagate through multiple levels of function
calls, of course, not just one level as shown here -- the try/except
could equally well be in a function that calls use_a_foo, for example.

Some people prefer to use assertions for argument-checking (ie. raise
AssertionError, unless __debug__ is false -- read the language
reference section on assert for more), regarding them as a way to
implement preconditions a la Bertrand Meyer & Eiffel.  I've never
really got my head around all the pros and cons there, TBH.


John




More information about the Python-list mailing list