[Python-Dev] Re: Sets: elt in dict, lst.include

Ka-Ping Yee ping@lfw.org
Wed, 31 Jan 2001 03:00:48 -0800 (PST)


On Wed, 31 Jan 2001, Thomas Wouters wrote:
> I still can't *see* this, though I
> wouldn't be myself if I hadn't tried to implement it anyway :) And I ran
> into some fairly mind-boggling issues. The worst bit is 'how the f*ck
> does FOR_LOOP know if something's a dict or a list'.

I believe the Pythonic answer to that is "see if the appropriate
method is available".

The best definition of "sequence-like" or "mapping-like" i can
come up with is:

    x is sequence-like if it provides __getitem__() but not keys()
    x is mapping-like if it provides __getitem__() and keys()

But in our case, since we need iteration, we can look for specific
methods that have to do with just what we need for iteration and
nothing else.  Thus, e.g. a mapping-like class without a values()
method is no problem if we never ask to iterate over values.

> And the
> almost-as-bad bit is 'WTF to do for user classes, extension types and
> almost-list/almost-dict practically-builtin types

I think it can be done; the draft PEP at

    http://www.lfw.org/python/pep-iterators.html

is a best-attempt at supporting everything just as you would expect.
Let me know if you think there are important cases it doesn't cover.

I know, the table

    mp_iteritems    __iteritems__, __iter__, items, __getitem__
    mp_iterkeys     __iterkeys__, __iter__, keys, __getitem__
    mp_itervalues   __itervalues__, __iter__, values, __getitem__
    sq_iter         __iter__, __getitem__

might look a little frightening, but it's not so bad, and i think
it's about as simple as you can make it while continuing to support
existing pseudo-lists and pseudo-dictionaries.  No instance should
ever provide __iter__ at the same time as any of the other __iter*__
methods anyway.


-- ?!ng

"The only `intuitive' interface is the nipple.  After that, it's all learned."
    -- Bruce Ediger, on user interfaces