[Python-ideas] OrderedDict literals

Andrew Barnert abarnert at yahoo.com
Wed Mar 19 19:08:54 CET 2014


On Mar 19, 2014, at 0:39, Anthony Towns <aj at erisian.com.au> wrote:

> class InterestingFields(OrderedDict):
>   def __init__(self, extras):
>       super(InterestingFields, self).__init__()
> 
>       D_key = D("key")
>       D_name = D("name")
>       s = S()
>       t = T()
>       f = self
> 
>       f["project"] =      D_key
>       f["issuetype"] =    D_name
>       f["summary"] =      s
>       # 18 more key/value pairs ...
> 
>       for k,v in extras:
>           f[k] = v
> 
> where D,S,T are classes that provide functions to convert from the
> Jira REST representation to the python version of the YAML
> representation I want and vice-versa.

My first question is: why are you retrieving all 21 fields into named variables, and then putting them all into the dict? Why not just:

   f["project"] = D("key")

Also, why does this have to be an OrderedDict in the first place? This isn't a collection of arbitrary fields where you want to preserve the order you found them in, it's primarily a collection of a fixed set of fields, which may have some extra fields at the end. In other words, an object. 

If the only issue is that you want to dump all your fields to YAML, you just need a reduce-type method that dumps them in the right order. You could do that in a variety of different ways; using an OrderedDict for your instance __dict__ is the obvious one, but your could also use a namedtuple instead of a normal class, use __slots__ (and store the extras in a single OrderedDict attribute), etc.

If the problem is how to take the extras in a way that's nicer than an iterable of pairs so you don't need all those parens and brackets when you construct it, you can remove either the brackets or the parens or both by just using *extras at the end and taking the pairs as args, or taking the keys and values as alternating args.

I don't mean to nitpick here, but I suspect this is exactly the kind of thing people were expecting--use cases that do unpythonic things like blur the line between objects and dicts ala JavaScript. Of course when you're dealing in JSON, or to some extent YAML, it's hard to completely avoid that blurring, but blurring it even farther isn't the solution.


More information about the Python-ideas mailing list