Clean way to not get object back from instantiation attempt gonebad

T

tobiah

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
 
T

tobiah

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)
 
S

Simon Forman

tobiah said:
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)

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
 
J

John Machin

tobiah said:
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)

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
 
B

Ben Finney

tobiah said:
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.
... """ Exception thrown from bad consumption """
... ... def __init__(self, left_thing, right_thing):
... if left_thing == 'grapes':
... raise ConsumptionError("Problem with consumption of fruit")
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
... myfoo = Foo('grapes', 'oranges')
... except ConsumptionError, e:
... myfoo = None
... None
 
S

Steve Holden

tobiah said:
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?
There's no way that the __init__() method can change the object of which
it's a method, since self is a variable local to the method (so changing
it won't change the object) and the method is required to return None.

regards
Steve
 
J

John Machin

Simon said:
|>> class f:
... def __init__(self):
... del self

Of course nothing happens. Args are local variables. 'self' is is a
vanilla arg of a vanilla function.
...
|>> e = f()
|>> e
<__main__.f instance at 0xb7dd91ec>


|>> class f:
... def __init__(self):
... return None

Of course nothing different happens. There is always an implicit
"return None" when control falls off the end of a function. Making it
explicit changes nothing.
...
|>> e = f()
|>> e
<__main__.f instance at 0xb7dd934c>

The whole idea of "del self" or "return None" is not a goer. "self" is
a reference to the (mutable) newly created object. After __init__ has
finished mutating it, the constructor will return the object to the
constructor's caller.

The whole idea that None should be returned in the event of error is
.... well, let's just say it leaves me speechless.
But you could raise an exception and check for it:

|>> class f:
... def __init__(self, flag=True):
... if not flag:
... raise

Please read the manual. A lone "raise" does *not* raise an anonymous
exception; it re-raises an exception that has just been trapped. If
there are none, it raises None, which causes (as documented) a
TypeError.
...
|>> def f_factory(flag):
... try:
... e = f(flag)
... except:

Blanket exception catching is *never* a good idea. In this case the
exception being caught is an artifact of your use of the unadorned
"raise".

If you inserted here:
.... import sys
.... x, y = sys.exc_info()[:2]
.... print x, y
you would get:
exceptions.TypeError exceptions must be classes, instances, or strings
(deprecated), not NoneType
... e = None
... return e
...
|>> foo = f_factory(True)
|>> foo
<__main__.f instance at 0xb7dd944c>
|>> foo = f_factory(False)
|>> foo
|>> print foo
None

HTH,
John
 
S

Steven D'Aprano

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?

I don't believe so.

Generally, in the event of an error, you should raise an exception:

class Foo():
def __init__(self, *fruits):
if "grapes" in fruits:
raise AllergyError("I'm allergic to grapes")
# process fruits

Then handle the exception:

try:
myfoo = Foo('grapes', 'oranges')
except AllergyError:
# recover gracefully
handle_failed_instance()


If you wish, you can wrap it in a function:

def safe_foo(*fruits):
try:
return Foo(*fruits)
except AllergyError:
return None

myfoo = safe_foo('grapes', 'oranges')

The disadvantage of this is now your code has to be sprinkled with a
million tests "if myfoo is not None: process(myfoo)".


Would the
__init__() just do del(self), or is there
a better way to think about this?


An alternative is to use a propagating "not a Foo" Foo object, like NaNs
and INFs in floating point.

class Foo():
def __init__(self, *fruits):
if "grapes" in fruits:
self._state = "failed" # NaNs use special bit patterns
else:
# process fruits
self._state = "okay"
def method(self, *args):
if self._state != "failed":
# process instance
else:
pass # do nothing
def __add__(self, other):
if self._state == "failed":
return self
elif other._state == "failed":
return other
else:
# process Foo addition
return something

Now you can call Foo methods regardless of whether the instance is valid
or not, errors will propagate cleanly, and you only need to check whether
the instance is valid at the very end of your code.

However, unless there is a clear advantage of doing this, you're creating
a fair bit of extra work for yourself.
 
S

Simon Forman

John said:
Of course nothing happens. Args are local variables. 'self' is is a
vanilla arg of a vanilla function.

I know.
Of course nothing different happens. There is always an implicit
"return None" when control falls off the end of a function. Making it
explicit changes nothing.

I know
The whole idea of "del self" or "return None" is not a goer. "self" is
a reference to the (mutable) newly created object. After __init__ has
finished mutating it, the constructor will return the object to the
constructor's caller.

I know that too.
The whole idea that None should be returned in the event of error is
... well, let's just say it leaves me speechless.

Tell me about it.
Please read the manual. A lone "raise" does *not* raise an anonymous
exception; it re-raises an exception that has just been trapped. If
there are none, it raises None, which causes (as documented) a
TypeError.

I know
Blanket exception catching is *never* a good idea. In this case the
exception being caught is an artifact of your use of the unadorned
"raise".

I know
If you inserted here:
... import sys
... x, y = sys.exc_info()[:2]
... print x, y
you would get:
exceptions.TypeError exceptions must be classes, instances, or strings
(deprecated), not NoneType
Yep.
... e = None
... return e
...
|>> foo = f_factory(True)
|>> foo
<__main__.f instance at 0xb7dd944c>
|>> foo = f_factory(False)
|>> foo
|>> print foo
None

HTH,
John

The entire post was meant as a pedantic exercise illustrating what not
to do (and how easy it is to figure that out with an interactive
session,) and sketching how to raise and check for an error instead.

In the three seconds I spent thinking about it, I couldn't decide what
exception to raise, so I used the wicked bare raise and except. I'm
certainly not advocating their use, but perhaps I should've made that
plain in a post intended to be "educational".

In any event, with your comments it's out there now, and the
educational value of this entire thread has been improved. Thanks
John.

Peace,
~Simon
 
J

John Machin

Simon said:
The entire post was meant as a pedantic exercise illustrating what not
to do (and how easy it is to figure that out with an interactive
session,) and sketching how to raise and check for an error instead.

Lessons usually start with the teacher asserting authority and stating
the objective of the lesson, especially if the main content is a list
of things the students should *not* do. Otherwise, casual observers can
only apply duck-typing :)

et pax vobiscum ...
 
G

Georg Brandl

tobiah said:
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?

There is a way, of course, that results in myfoo
being None in case of an error, but it is not a one-liner and
I'd not recommend it.
If something goes wrong, raising an exception is the best thing to do.

Georg
 
O

olsongt

tobiah said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top