making a class return None from __init__

Erik Max Francis max at alcyone.com
Fri Oct 4 17:56:16 EDT 2002


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

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ We'll have to make our own luck from now on.
\__/ Louis Wu
    The laws list / http://www.alcyone.com/max/physics/laws/
 Laws, rules, principles, effects, paradoxes, etc. in physics.



More information about the Python-list mailing list