wim wim - 5 months ago 14
Python Question

Initialising a QueryDict.fromkeys

We can initialise a new dict instance from a list of keys:

>>> dict.fromkeys(['spam', 'spam', 'potato'])
{'potato': None, 'spam': None}


And a querydict is a dict, so this should work, right?

>>> QueryDict.fromkeys(['spam', 'spam', 'potato'])
TypeError: __init__() takes at least 2 arguments (1 given)


Of course I can do something lame like
QueryDict('spam&spam&potato')
, but my question: is the
.fromkeys
method usable at all, or completely broken?

If the former, how do you use it? If the latter, why wasn't it explicitly disabled in the subclass?

wim wim
Answer

tl;dr QueryDict.fromkeys will start working in the Django 1.11 release.

At PyCon 2016 I had the opportunity to speak with some core Django developers, we agreed the inherited method is broken and violates the Liskov substitution principle. At one of the sprints I was able to scratch this itch and patch the QueryDict class.

Here's the relevant commit and issue, the fix is now merged into master and already in the docs. I used an implementation similar to the first proposal from hynekcer.

Comments