PEP 234: Iterators
Peter Caven
p.caven at ieee.org
Wed May 2 18:03:55 EDT 2001
"Michael Hudson" <mwh21 at cam.ac.uk> wrote in message
news:m3k8408165.fsf at atrus.jesus.cam.ac.uk...
> "Peter Caven" <p.caven at ieee.org> writes:
>
--snip--
>
> I *think* the problem with this is that we want to write:
>
> if key in dict:
> ...
>
> You're almost never going to want to write "if item in dict", and
> having different meanings for "x in dict" in different contexts would
> be insane.
>
Well, I didn't think that:
if key in dict.iterkeys():
would be a problem. I guess I'm assuming that the keys iterator for
dictionaries would allow that.
And, we still have:
if dict.has_key(key) :
anyways. I'm not sure that 'if key in dict' would be that much better.
> On reflection, I think I think (<wink>) of dicts more as containing
> keys, and associating data with each key. I don't think of them as
> containing pairs.
I'm heavily influenced by the STL here :-)
>
> > This would open up some further interesting possibilities such as
specifying
> > either the key or the value
> > as an object implementing the __eq__ operation in various ways (regular
> > expressions, etc...).
> > ... but I'm sure you've all already thought of that: :-)
>
> Eh?
>
I mean, if a class was written:
class KeysLessThan:
def __init__(self, limit):
self.limit = limit
def __eq__(self, key):
return (key < limit)
then we could write (for example):
if KeysLessThan(10) in dict.iterkeys :
would allow some testing for existence in arbitrary ways.
I would really like to be able to write a loop over only the keys, values or
items in a dict
that pass some test (filter):
for KeyFilter(),value in dict:
...do something with the values that have keys that pass the filter.
I know this idea is half-baked. Is there some other way of elegantly doing
this without doing an explicit test inside the loop?
> Cheers,
> M.
>
Regards,
-- Peter.
More information about the Python-list
mailing list