making a class return None from __init__
Martin v. Loewis
martin at v.loewis.de
Fri Oct 4 16:50:31 EDT 2002
Rajarshi Guha <rajarshi at presidency.com> writes:
> Is there any way to make the constructor return a None object?
No. When __init__ is invoked, the object it "returns" is already
determined - it is the self object. You cannot change the identity of
this object, or the fact that it is an instance object, you can only
modify it.
Therefore, the return value of __init__ is irrelevant. Python checks
that applications do not attempt to "return" something from __init__:
If there is a non-None return value, Python raises an error.
If you want a constructor to fail, instead of completing, consider to
raise an exception. If you want Graph(foo) to return None, make Graph
a function:
class _Graph:
def __init__(self,v):
pass
def Graph(v):
if SOME_TEST:
return None
return _Graph(v)
If you absolutely must have a type whose constructor returns None,
implement a type that inherits from object, and implement an __new__.
HTH,
Martin
More information about the Python-list
mailing list