Trouble when overloading operator[ ]

Grant Edwards ge at nowhere.none
Fri Jul 21 12:37:22 EDT 2000


In article <8l9qfp$gc6$1 at nnrp1.deja.com>, david_ullrich at my-deja.com wrote:

>> You're using a single index whose value is the expression 2,3.
>> The expression 2,3 evaluates to a tuple, which is passed to
>> _getitem__, just as would the value of any other expression
>> used as an index.
>
>  Ok, then I should revise what I said: You can use the
>notation [2,3] to accomplish the same thing.
>
>  No doubt you're exactly right. But evidently there's a
>difference between [] indices and function parameters here:
>
>def hmm(x):
>	return x
>
>print hmm(2,3)
>
>gives an error (hence my suspicion that someone might
>expect whatever[2,3] to give an error without trying it...)
>
>  Why is "2,3" a single expression in whatever[2,3]
>but not in hmm(2,3)?

Because that's the way the language syntax is defined.  :)

The syntax for a function call includes the commas separating
the parameters.  The syntax for an index doesn't include any
commas, so the commas are part of an expression yeilding a
tuple.  It would be a bit more obvious if one used foo[(4,5)].

A comma may be one of (three things (at least)):

 1) token seperating function arguments
 2) token seperating literal list items
 3) tuple construction operator

Deciding which function is being performed by a particular
comma requires you to look at the context.  There are several
special contexts -- if none of them is in effect, then a comma
is a tuple constructor operator.   There is a shortage of
delimiters and operators, so '(' has three usages...

            Function call:  foo(3)
              Empty tuple:  ()
      Expression grouping:  (4+4)*5

'[' has two usages...

                 Indexing:   foo[4]
  Literal list delimiters:   [4,5,9]
         
',' has three usages...

       Tuple construction:   4,5,6
           List seperator:   [4,5,6]
      Parameter seperator:   foo(4,5,6)

The last example is potentially ambiguous, since it could be
either a single parameter whose value is the expression 4,5,6
or it could be three seperate parameters.  Python syntax is
defined such that it is the latter.  If you want the former,
you've got to add parens (in their expression grouping mode):

   foo((4,5,6))

The triple-overloading of commas and parenthesis is
unfortunate, but as the matrix users will attest, there is a
dire shortage of operators and delimiters in the 7-bit ASCII
character set.

I vote we switch to the APL character set...

-- 
Grant Edwards                   grante             Yow!  Now I am depressed...
                                  at               
                               visi.com            



More information about the Python-list mailing list