Clean way to not get object back from instantiation attempt gone bad

John Machin sjmachin at lexicon.net
Tue Aug 15 20:19:50 EDT 2006


tobiah wrote:
> I should have made it more clear that Foo is a class:
>
>
> class Foo:
>
> 	def __init__(self, *args):
>
> 		for arg in args:
> 			if is_fruit(arg):
> 				del(self)
>
>
>
> tobiah wrote:
> > Suppose I do:
> >
> >
-*> > myfoo = Foo('grapes', 'oranges')
> >
> > And in the __init__() of Foo, there is
> > a real problem with the consumption of fruit.
> > Is there a clean way to ensure that myfoo
> > will be None after the call?  Would the
> > __init__() just do del(self), or is there
> > a better way to think about this?
> >

Yes. Raise an exception, with details of what the problem is -- which
arg? what (out of multiple possible problems) is wrong with it?

if self.is_fruit(arg):
    raise FooError("I don't eat fruit: %r" % arg)
if self.some_other_problem(arg):
    raise FooError("Some other problem: %r" % arg)

HTH,
John




More information about the Python-list mailing list