making a class return None from __init__

Alex Martelli aleax at aleax.it
Sat Oct 5 06:16:00 EDT 2002


Erik Max Francis wrote:

> Rajarshi Guha wrote:
> 
>>   I have a class which makes some basic error checks in the __init__
>> function. Ideally, if the parameters passed to the __init__ function
>> fail
>> the checks I would like to return a None. But this does'nt seem to
>> happen:
> ...
>> (where v will fail) I always get <__main__.Graph instance at 0xXXXXXX>
>> Is there any way to make the constructor return a None object?
> 
> The return value of constructors is not used for anything; besides, the

Hmmm, it's used to check that it's None and give an exception otherwise...:

[alex at lancelot ba]$ python
Python 2.3a0 (#1, Oct  4 2002, 13:05:05)
[GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class X:
...   def __init__(self):
...     return 1
...
>>> x = X()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __init__() should return None
>>>

That's probably what you mean, but I just thought I'd clarify it.

> default return value of any function without an explicit return
> statement is None in the first place.
> 
> The proper way to handle this case is to raise an exception from the
> constructor if something goes wrong.  If you so desired you could wrap
> the creation of the object in a secondary function which catches the
> error and returns None instead of it catches an error:
> 
> def protectedGraph(v):
> try:
> return Graph(v)
> except SomeError:
> return None

Yes to all of this -- a factory function of some kind or another is
the best approach when you're not sure what type of object you want
to generate (and None is a different type from Graph, so this is
a case in point:-).  In modern Python you can dress up such a
function as a class's static method __new__, but keeping it as a
separate function is often preferable anyway -- clearer, simpler,
more portable to older Python versions (e.g., the current release
of Jython, which still implements the Python 2.1 language).


Alex




More information about the Python-list mailing list