__getitem__ and arguments

François Pinard pinard at iro.umontreal.ca
Sat Jul 19 15:23:42 CEST 2003


[KanZen]

> >>> class A(object):
>       def __getitem__(self, *args):
>         print len(args)

> >>> a=A()
> >>> a[1, 2, 3]
> 1

> For __getitem__() the arguments become a tuple.  I can't seem to find this
> in the language spec.  Can anybody explain this to me?

Hello, KanZen.

When you write an argument list as `*args', you _always_ get a tuple
of all arguments.  Normally, one writes:

    def __getitem__(self, argument):
        ...

as `__getitem__' only accepts one argument besides `self'.  Of course,
you may well write:

    def __getitem__(self, *arguments):
        ...

but then, `arguments' will always be a 1-tuple in practice, and
`arguments[0]' will contain the actual argument.

This being said, consider the call `a[1, 2, 3]' (it does not look like a
call, but we both know that under the scene, this is calling `__getitem__').
We may be tempted to think that it works a bit the same as an explicit
function call would work, like if it was written `a(1, 2, 3)', and the
confusion might come from there.  Indeed, in `a(1, 2, 3)', there are three
arguments.  `a[1, 2, 3]' is not the same, it calls the `__getattr__' of `a'
with a _single_ argument `1, 2, 3'.  That single argument is really a tuple
itself.

Many Python users like to write tuples as `(1, 2, 3)', using superfluous
parentheses for strange reasons. :-) They would likely write `a[(1, 2, 3)]'
as a way to over-stress that `a[]' accepts only one value within the
brackets.  The writing `a[1, 2, 3]' is very legible because it is less
noisy, and you are right in preferring it.  Yet you have to remember that
`1', `2' and `3' are not to become separate arguments for `__getitem__'.
The single argument will be what was within brackets, that is, a tuple.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list