Suggestion: make sequence and map interfaces more similar
Steven D'Aprano
steve at pearwood.info
Wed Mar 30 22:44:47 EDT 2016
On Thu, 31 Mar 2016 03:52 am, Random832 wrote:
> Like, these are common patterns:
>
> for i, x in enumerate(l):
> # do some stuff, sometimes assign l[i]
>
> for k, v in d.items():
> # do some stuff, sometimes assign d[k]
for a, b in zip(spam, eggs):
# do some stuff, sometimes assign x[a] or b[a] or who knows what?
Does this mean that "lists, dicts and zip" should all support the same
interface?
Not every coincidental and trivial piece of similar code is actually
related.
> A way to apply that pattern generically to an object which may be either
> a sequence or a mapping might be nice.
Nice, and easy.
# Duck-typing version.
def iterpairs(obj):
if hasattr(obj, 'items'):
it = obj.items
else:
it = enum(obj)
yield from it
# Type-checking version.
def iterpairs(obj):
if isinstance(obj, collections.abc.Mapping):
it = obj.items
elif isinstance(obj, collections.abc.Sequence):
it = enum(obj)
else:
raise TypeError('not a sequence or a mapping')
yield from it
Pick which one you prefer, stick it in your own personal toolbox of useful
utilities functions, and off you go.
--
Steven
More information about the Python-list
mailing list