making a class return None from __init__

sismex01 at hebmex.com sismex01 at hebmex.com
Fri Oct 4 16:24:38 EDT 2002


> From: Rajarshi Guha [mailto:rajarshi at presidency.com]
> 
> Hi,
>   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:
> 
> class Graph:
> 	
> 	def __init__(self,v):
> 		if SOME_TEST:
> 			return None
> 
> However when I test it out as:
> 
> g = Graph(v)
> print g
> 
> (where v will fail) I always get <__main__.Graph instance at 0xXXXXXX>
> Is there any way to make the constructor return a None object?
> 
> Thanks,
>

Hmmm... I believe you have a simple misunderstanding;
whatever value __init__() would return is irretrievably
lost (ok, enough drama), because __init__() is not called
to *create* the object, but to *initialize* it, the
object is already allocated by the time __init__() is
called.

What you *can* do is raise an exception, in which case
the assignment is aborted.

Good luck.

-gustavo













More information about the Python-list mailing list