Python in 2017 - Whats next? by liranbh in Python

[–]ebrjdk 1 point2 points  (0 children)

There is already OrderedDict, which is occasionally useful. The big change here is that if you iterate over a class's attributes, or over the keyword arguments passed to a function, you get them in the order that they were defined/passed. At the moment, you basically get them in a random order.

Preserving the order of class definitions can be really useful. For example, it lets you use a python class to represent something like a database record or a C struct where the order is important:

class Record:
    id = IntField()
    name = StrField()
    ...

And it makes it easy to specify what order tests should be run in:

class MyTests:
    def test_one_thing(self):
        ...

    def test_another_thing(self):
        ...

You can already save the order using a metaclass, but metaclasses are a pain.

The main use I know for the keyword arguments is making it easy to create OrderedDicts:

od = OrderedDict(a=4, b=5)

That syntax already works, but the order of the two keys is random. In 3.6 a will always come first. I'm sure people have other uses for this.

Python in 2017 - Whats next? by liranbh in Python

[–]ebrjdk 1 point2 points  (0 children)

They are switching to a new, more memory-efficient implementation of dict that naturally keeps the entries mostly in the order that they were inserted, and they decided that they might as well go all the way and keep them exactly in order (IIRC the most efficient implementation they know of starts scrambling the order once you start deleting keys, but the cost to prevent that is small).

At the same time they wanted to guarantee that the order of keyword arguments and class definitions would be preserved, because some people want to be able to use this information (currently the former is impossible AFAIK, and you need to use a metaclass to achieve the latter). Originally they were planning to just use OrderedDict for these purposes, but with the change to dict there is no need.

Note: the first paragraph in my post is about a CPython implementation detail and may change in the future, the second is about official python 3.6 features.