[Python-ideas] Dict literal use for custom dict classes

Ryan Hiebert ryan at ryanhiebert.com
Sat Dec 12 19:44:12 EST 2015


> On Dec 12, 2015, at 18:13, Jelte Fennema <me at jeltef.nl> wrote:
> 
> I really like the OrderedDict class. But there is one thing that has always bothered me about it. Quite often I want to initialize a small ordered dict. When the keys are all strings this is pretty easy, since you can just use the keyword arguments.

I don't think this will work. Python uses a dict to pass in kwargs, so you've already lost ordering at that point, if I'm right.

> [...] I have two suggestions for language additions that fix that. 
> The first one is the normal dict literal syntax available to custom dict classes like this:
> OrderedDict{1: 'a', 4: int, 2: (3, 3)}

My first preference would be for the proposals for dict to become ordered by default to come to fruition. If that turns out to be unacceptable (even though, as I understand it, PyPy has already been able to do this), then this looks pretty good to me. It's and alternate call operator that uses dict-like syntax to pass in a tuple of pairs.
> 
> [...]
> 
> A second very similar option, which might be cleaner and more useful, is to make this syntax available (only) after initialization. So it could be used like this:
> d = OrderedDict(){1: 'a', 4: int, 2: (3, 3)}
> d{3: 4, 'a': 'c'}
> >>> OrderedDict(){1: 'a', 4: int, 2: (3, 3), 3: 4, 'a': 'c'}

IMO, this is strictly worse than the other option. It's confusing that the call operator wouldn't happen before this dict-like call.

Either would be unneeded if dict was ordered by default, and it's far and way the best option, IMO.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151212/25427216/attachment.html>


More information about the Python-ideas mailing list