Can __init__ not return an object?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Apr 22 02:14:33 EDT 2007


On Sat, 21 Apr 2007 22:36:42 -0400, Steven W. Orr wrote:

> When I go to create an object I want to be able to decide whether the 
> object is valid or not in __init__, and if not, I want the constructor to 
> return something other than an object, (like maybe None).

None is an object, like everything else in Python.

__init__ is not a constructor, it is an initializer -- by the time
__init__ is called, the instance is already constructed.

__init__ is expected to return None. 

>>> class Foo(object):
...     def __init__(self):
...             return 2
...
>>> f = Foo()
__main__:1: RuntimeWarning: __init__() should return None



> I seem to be 
> having problems. At the end of __init__ I say (something like)
> 
>  	if self.something < minvalue:
>  	    del self
>  	    return None
> 
> and it doesn't work.

del self doesn't really do anything useful there, except unbind the name
"self" from the instance.

"return None" is redundant, because all functions and methods will
automatically return None if you don't specify differently.



> I first tried just the return None, then I got crafty 
> and tried the del self. Is what I'm trying to do possible in the 
> constructor or do I have to check after I return? Or would raising an 
> exception in the constructor be appropriate?

Yes, absolutely raise an exception.



-- 
Steven.




More information about the Python-list mailing list