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

John Machin sjmachin at lexicon.net
Tue Aug 15 20:57:51 EDT 2006


Simon Forman wrote:

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




More information about the Python-list mailing list