Clean way to not get object back from instantiation attempt gone bad
Ben Finney
bignose+hates-spam at benfinney.id.au
Tue Aug 15 20:26:12 EDT 2006
tobiah <st at tobiah.org> writes:
> 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?
I'm not sure I understand your goal, but it seems that you want to
handle two cases: one where Foo can be properly initialised, and one
where it can't -- an error condition.
That sounds like a job for exceptions.
>>> class ConsumptionError(ValueError):
... """ Exception thrown from bad consumption """
...
>>> class Foo(object):
... def __init__(self, left_thing, right_thing):
... if left_thing == 'grapes':
... raise ConsumptionError("Problem with consumption of fruit")
...
>>> myfoo = Foo('zucchini', 'spam')
>>> print myfoo
<__main__.Foo object at 0x401e446c>
>>> myfoo = Foo('grapes', 'oranges')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in __init__
__main__.ConsumptionError: Problem with consumption of fruit
>>> try:
... myfoo = Foo('grapes', 'oranges')
... except ConsumptionError, e:
... myfoo = None
...
>>> print myfoo
None
--
\ Rommel: "Don't move, or I'll turn the key on this can of Spam!" |
`\ -- The Goon Show, _Rommel's Treasure_ |
_o__) |
Ben Finney
More information about the Python-list
mailing list