From: dolio@... (Dan Doel) Date: 2003-08-15T10:11:29+09:00 Subject: Re: Overloading () "Dave Benjamin" wrote > > I know you can overload () in C++, but can you overload () in Python? > > Yes, it's quite simple, actually: > > class CallableClass: > def __call__(self): > print 'Hey there!' > > cc = CallableClass() > cc() > > Output: > "Hey, there!" > > > Seems like allowing overloading of () is a potential tarpit... and there > > are potential parser issues as well, but I defer to matz to answer your > > question. > > I won't comment on whether the ability to overload () is good or bad, > necessarily (although it would be nice if Ruby's lambdas had normal > functional semantics), but I would be very interested in understanding the > issue from a language design standpoint, if you'd be so kind, Matz. I will comment that although being able to overload () in ruby could make it more consistent, it wouldn't exactly give it totally normal functional syntax. Since in ruby you can call functions like: fun a, b, c Without parentheses at all. Detecting such a case might be even more difficult than the () case (I don't really know), which might be why it's not implemented (is it better to have half of normal syntax, or none at all?). Changing objects to automatically respond to a call method in the above case would be qutie interesting, though, since you could actually curry functions in that case, writing fun a b c Assuming it binds in the correct order. Currently currying looks like fun[a][b][c], or with function syntax fun(a)(b)(c), which is somewhat cryptic. If one is supporting callable objects, one might also look at the expression: foo.a() and say, "Does foo.a represent a method call, or does foo.a represent the method object on which the () operator is being used?" In other words, should ruby support: fun_obj = foo.a fun_obj() Or should it stay with: fun_obj = foo.method(:a) ? The former requires that all methods be called with () in order to get the value which I think would upset a lot of people, since it destroys accessors that ruby has (i.e. foo.a is an accessor for the @a instance variable, but foo.a _looks_ like you're simply accessing a public variable). The first scheme supports more transparent first-class functions, but it comes at a big cost. So, as you can see, implementing an overloadable () is a big can of worms. There's no immediate way to tell if foo() is a direct function call or a callable object, or in bar.a(), whether a() is a function call, or whether a is a function that returns a callable object that is being called (which it probably wouldn't be). So, letting you overload () is of debatable value at best. It would at the very least make things much more complex. Food for thought. - Dan