() vs. [] operator

Xavier Ho contact at xavierho.com
Thu Oct 15 03:51:15 EDT 2009


On Thu, Oct 15, 2009 at 5:14 PM, Ole Streicher <ole-usenet-spam at gmx.net>wrote:
<snip>

> So what is the reason that Python has separate __call__()/() and
> __getitem__()/[] interfaces and what is the rule to choose between them?


Hi,

This is very interesting, a thought that never occured to me before.
Usually, a function is a function; an array (list, iterator, whatever you
have) is, well, an array of data. You access them by index.

Mathematically speaking, functions are usually continuous. For any given
continuous function, you can give it any value of input (1, 0.1, or even
0.000001) and it'll give you one output. But obviously we don't call an item
from index 0.1, but 0, 1, 2, 3, and so on. That's probably the first sign
where your function might be best fitted.

Also, one would normally expect a __getitem__() call to be very fast; it
would be awkward to return A[10000] a hundred times slower than A[1]. That
said, it's a simple constant-time look up. That'll give you another clue
when to distinquish the two functions.

The other way also works; if a function takes any floating/decimal number,
usually we expect it to be callable, with the () operator.

I can think of funky things like to memorise every function call that has
been done, and look up the memory if this same input has been called before;
it might speed up some calculation for certain purposes. All in all, a good
idea to separate the two operators.

Cheers,
Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091015/ec1b6992/attachment-0001.html>


More information about the Python-list mailing list