() vs. [] operator

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Oct 15 09:49:00 CEST 2009

On Thu, 15 Oct 2009 09:14:35 +0200, Ole Streicher wrote:

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

They are separate so you can implement both, or just one, or neither, 
whichever makes the most sense for your data type.

If something is function-like, then implement __call__. If something is 
sequence- or dictionary-like, then implement __getitem__. If it's both, 
then make an arbitrary choice of which one you want to support, or 
implement both, whichever you prefer.

The best thing to do is follow the lead of build-in objects. For example, 
chr() is a function which takes an integer and returns a character, but 
it makes little sense to think of it as a table of values. You wouldn't 
sensibly expect to do something like:

chr[32:39] = 'abc'

and have the table replace chars ' !"#$%&' with 'abc' (changing the 
length of the table). Even if chr() is implemented as a table internally, 
it's actually a function.

Contrast that with xrange objects, which are implemented as lazy 
sequences, i.e. something like a function. But xrange objects themselves 
(not the xrange function) use the sequence interface:

>>> obj = xrange(23, 42)
>>> obj[10]

with the limitation that it doesn't support slices.


More information about the Python-list mailing list