Clean way to not get object back from instantiation attempt gone bad
olsongt at verizon.net
olsongt at verizon.net
Fri Aug 18 10:02:22 EDT 2006
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
As others have said, just raise an exception. You can hide
instantiation inside a factory function to simulate the behaviour
you're specifically talking about:
class Foo:
def __init__(self, *args):
for arg in args:
if is_fruit(arg):
raise RuntimeError("I don't like fruit")
def FooFactory(*args):
try:
return Foo(*args)
except RuntimeError:
return None
-Grant
More information about the Python-list
mailing list