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

Simon Forman rogue_pedro at yahoo.com
Tue Aug 15 20:07:51 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?
> >
> > Thanks,
> >
> > Toby
> >
>

I don't think there is a way to do this (but I could be wrong):

|>> class f:
...     def __init__(self):
...             del self
...
|>> e = f()
|>> e
<__main__.f instance at 0xb7dd91ec>


|>> class f:
...     def __init__(self):
...             return None
...
|>> e = f()
|>> e
<__main__.f instance at 0xb7dd934c>

But you could raise an exception and check for it:

|>> class f:
...     def __init__(self, flag=True):
...             if not flag:
...                     raise
...
|>> def f_factory(flag):
...     try:
...             e = f(flag)
...     except:
...             e = None
...     return e
...
|>> foo = f_factory(True)
|>> foo
<__main__.f instance at 0xb7dd944c>
|>> foo = f_factory(False)
|>> foo
|>> print foo
None

There might be a way using __new__(), but I don't know what or how.

Also, "del" is a statement, not a function.  You don't need to use
()'s.

HTH,
~Simon




More information about the Python-list mailing list