Generic dictionary
Thorsten Kampe
thorsten at thorstenkampe.de
Sun Nov 20 07:49:38 EST 2016
* Steve D'Aprano (Sun, 20 Nov 2016 22:40:19 +1100)
>
> Further thoughts come to mind, after looking more closely at your code.
>
> On Sun, 20 Nov 2016 08:27 pm, Thorsten Kampe wrote:
>
> > def values(inst):
> > if isinstance(inst._generic, dict):
> > return inst._generic.values()
> > else:
> > try:
> > return list(zip(*inst._generic))[1]
> > except IndexError: # empty GenericDict
> > return ()
>
> That's... weird. Sometimes your instance will return a list, and sometimes a
> tuple. So if you write code expecting a list, it will suddenly and
> unexpectedly break when the instance is empty.
>
> A better way of writing this is:
>
> def values(inst):
> if isinstance(inst._generic, dict):
> return inst._generic.values()
> else:
> return [t[1] for t in inst._generic]
You are right, I modified it to
`return [value for key, value in inst._generic]`
...which is more more intelligible than my original try/except/list
(zip)
Thanks, Thorsten
More information about the Python-list
mailing list