no return values for __init__ ??
Helge Hess
helge at mdlink.de
Thu Jan 6 16:31:06 EST 2000
Aahz Maruch wrote:
> In article <3874CFE5.765A40EA at mdlink.de>,
> Helge Hess <helge.hess at mdlink.de> wrote:
> >recently I was heavily wondering why __init__ does not allow return
> >values ! Is there any special reason not to do this ?
>
> Yup. The return value *has* to be the object instantiated by Python.
No, the return value has to be None, which is the default return value
as well. The only thing enforcing this from a technical point of view is
a simple
if (ret != Py_None)
throw exception
in the PyInstance_New() function. The 'fix' is just
if ((ret == Py_None) || (ret == self))
decref(ret), return self
else
decref(self), return ret
This doesn't break compatibility to any valid Python code.
> Why do you want to do this?
There are some applications all of which could be more or less solved by
using factories at the expense of a more complex & inconvenient
interface to the functionality (you have to learn two classes instead of
just one).
I can give just three:
1. singletons
_C = None
class C:
def __init__(self):
if _C is None: _C = self
return _C
a = C()
b = C()
a and b are the same objects, the user of C() doesn't need to know
about that
2. interns
str2object = {}
class String:
def __init__(self, str):
if not str2object.has_key(str):
self.value = str
str2object[str] = self
return str2object[str]
a = String("abc")
b = String("def")
c = String("abc")
a and c will be identical.
3. class clusters (as they are called in Objective-C)
class String: # abstract
def __init__(self, data, encoding="python"):
if encoding == "utf8": return Utf8String(data)
elif encoding == "utf16": return Utf16String(data)
elif encoding == "python": return data
else: raise UnsupportedEncoding
a = String("hhuu", encoding="utf16")
v = String("sdfhjsh")
The nice thing is that the user only has to care about String,
the __init__ function will return an appropriate subclass on
demand. What an 'appropriate subclass' is, is abstracted from
the user pov.
My major feeling why __init__ should be allowed to return values
anyway is, that __init__ is a usual method and should be treated
as such.
Greetings
Helge
More information about the Python-list
mailing list