() vs. [] operator

Ulrich Eckhardt eckhardt at satorlaser.com
Thu Oct 15 04:32:15 EDT 2009


Ole Streicher wrote:
> I am curious when one should implement a "__call__()" and when a
> "__getitem__()" method.
> 
> For example, I want to display functions and data in the same plot.

Wait: The term 'function' is overloaded. In Python and programming in
general, a function is a piece of code with optional input, output and side
effects. Alternative names are procedure, operation, subroutine.

In mathematics, the term 'function' refers to an algorithm that takes some
parameters, transforms them and returns a result. Note that here no side
effects can ever occur and that you always have both input parameters and
output parameters. Also, a mathematic function will always yield the same
results for the same input, which is basically a result from not having
side effects and not having variables at all.

> For a function, the natural interface would to be called as "f(x)",
> while the natural interface for data would be "f[x]".

In math, a function invocation is written f(x). Since this is a mere
retrieval of a value, regardless of how complicated the implementation may
be, I'd say that the natural syntax would be f[x] in Python. However, since
[] also supports writing a mapping and since an implementation may have a
significant overhead, I'd rather tend towards the function call syntax.

> On the other hand, whether a certain data object is a function or a
> data table is just an inner detail of the object (imagine f.e. a
> complex function that contains a data table as cache), and there is
> no reason to distinguish them by interface.
> 
> So what is the reason that Python has separate __call__()/() and
> __getitem__()/[] interfaces and what is the rule to choose between them?

As their name implies, one invokes a function (procedure, subroutine etc)
while the other retrieves an item from a mapping. I agree that the exact
difference is not really that easy to explain and that there are corner
cases.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list