[Python-ideas] Iteritems() function?
Nick Coghlan
ncoghlan at gmail.com
Wed Jun 8 18:24:30 CEST 2011
On Thu, Jun 9, 2011 at 1:41 AM, Mathias Panzenböck
<grosser.meister.morti at gmx.net> wrote:
> I don't think that is enough complexity to justify an inclusion in builtins
> or itertools. Anyway, I would have expected such a function to do this (so
> it's not even obvious):
>
> def items(sequence):
> if hasattr(sequence, 'items'):
> return sequence.items()
> else:
> return enumerate(sequence)
I expect the use case here is to implement APIs like the dict
constructor and update() method - you can either pass them a mapping,
or else an iterable of key-value pairs. As Oleg noted though, the
traditional way of handling that is to ducktype on the "items" method,
although an isinstance check against Mapping would indeed be an
acceptable substitute these days. Either way, calling items() gets you
an iterable of key-value pairs, so you write your algorithm to work on
that and do a coercion via items() to handle the mapping case.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list