Re: foo[] - mapping or sequence function called first?

Guido.van.Rossum@cwi.nl
Fri, 03 Feb 1995 14:54:21 +0100

> I've been bashing on the Python SNMP interface again, and I've hit a
> bit of a snag - one of the objects will offer both subscripting and
> the sequence 'item' method - these appear to take the same syntax, ie
> foo[1].
>
> I need the mapping subscript syntax for sub-identifiers (eg
> a.iso.org.dod.internet.mgmt['mib-2'].interfaces.ifNumber[0].get()
> (to pick a pathological example)) and it seems I need the sequence
> 'item' call to do Jack's suggested
>
> for i in s.interfaces.ifTable.ifEntry:
> do_some_tabular_magic()
>
> syntax.
>
> From fiddling a bit, it appears the way a 'for' loop is done is that
> the seq_item function is called with successively higher numbers
> until it returns 0. But wont this also then mean on a call, say, of
> foo.ifNumber[0], that the sequence_item function might get called?
>
> Testing it shows that the mapping subscript function always gets called
> in preference to the sequence item function, but I need to be sure that
> this will remain the case.

I presume you're referring to the function apply_subscript() in
Python/ceval.c, which applies the mapping-style subscription operator
if it exists, else the sequence-style subscription operator applies if
it exists.

I hadn't thought about this before, but after looking at it a little
bit, I can guarantee that it must be the case that the mapping
subscript operator has precedence over the sequence subscript
operator, because the mapping subscript operator is more general (and
all this is decided purely based on the type of the object being
subscripted -- the type of the subscript plays no role).

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>