Re: Why require __init__ to return None?

Steven Miale (smiale@cs.indiana.edu)
Sat, 28 May 1994 13:01:08 -0500

In article <9405272243.AA05427=guido@voorn.cwi.nl>,
<Guido.van.Rossum@cwi.nl> wrote:
>> I was thinking of the same thing. I would like to solve it in another
>> way, by introducing the operator __call__ for instances.
>
>This is indeed a useful extension. I might add it sooner or later
>-- sooner if someone contributes a working patch!

Here is a working diff to ceval.c:

*** ceval.c Sat May 28 12:32:14 1994
--- ceval.c Sat May 28 12:57:16 1994
***************
*** 2032,2037 ****
--- 2032,2048 ----
if (is_classobject(func)) {
return newinstanceobject(func, arg);
}
+ if (is_instanceobject(func)) {
+ object *res, *call = getattr(func,"__call__");
+ if (call == NULL) {
+ err_clear();
+ err_setstr(AttributeError, "no __call__ method defined");
+ return NULL;
+ }
+ res = call_object(call, arg);
+ DECREF(call);
+ return res;
+ }
err_setstr(TypeError, "call of non-function");
return NULL;
}

Some example output:

>>> class Iterator:
... def __init__ (self, list):
... self.list = list
... self.pos = -1
... def __call__ (self):
... self.pos = self.pos + 1
... return self.list[self.pos]
...
>>> class Dummy:
... pass
...
>>> x = Iterator([1,2,3,4,5])
>>> x()
1
>>> x()
2
>>> y = Dummy()
>>> y()
Traceback (innermost last):
File "<stdin>", line 1
AttributeError: no __call__ method defined

-- 
Steven Miale - smiale@cs.indiana.edu| I was there at the dawn of the third age
Indiana University, Bloomington, IN | of man, and all I got was this lousy .sig