[Python-ideas] Dict literal use for custom dict classes
Chris Angelico
rosuav at gmail.com
Tue Dec 15 08:19:58 EST 2015
On Wed, Dec 16, 2015 at 12:08 AM, Jelte Fennema <me at jeltef.nl> wrote:
> After thinking some more, I think you are right in saying that it would make
> more sense to let it represent an OrderedDict directly. Mostly because the
> mutability suggested by the square brackets. And also a bit because I'm not
> sure when a mapping that maps multiple values to the same key is actually
> useful.
>
> Secondly, I think your idea for namedtuple literals is great. This would be
> really useful in the namedtuple use case where you want to return multiple
> values from a function, but you want to be clear in what these values
> actually are. I think this would need to generate some kind of anonymous
> named tuple class though, since it would make no sense to have to create a
> new class when using a literal like this.
Be careful of this trap, though:
>>> from collections import namedtuple, OrderedDict
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(x=5, y=2)
>>> list(p)
[5, 2]
>>> od = OrderedDict((('x',5),('y',2)))
>>> list(od)
['x', 'y']
Dictionary-like things iterate over their keys; tuple-like things
iterate over their values. (And a list of pairs would effectively
iterate over items().) Having extremely similar syntax for creating
them might well lead to a lot of confusion on that point.
ChrisA
More information about the Python-ideas
mailing list