[Python-ideas] Let's be more orderly!
Ethan Furman
ethan at stoneleaf.us
Wed May 15 18:40:09 CEST 2013
On 05/15/2013 09:27 AM, Amaury Forgeot d'Arc wrote:
> 2013/5/15 Don Spaulding <donspauldingii at gmail.com <mailto:donspauldingii at gmail.com>>
>
> Even if the only ordering change that was made was to magically give OrderedDict.__init__ its **kwargs in order, it
> would clean up these instances, which I initially referred to as literals.
>
> foo = OrderedDict(
> b=1,
> a=2
> )
>
>
> Since PEP3115, classes can __prepare__ a custom dict:
>
> from collections import OrderedDict
> class OrderedDictBuilder(type):
> @classmethod
> def __prepare__(metacls, name, bases):
> return OrderedDict()
> def __new__(cls, name, bases, classdict):
> del classdict['__module__'] # ugh
> return classdict
>
> Then we can (ab)use the Class syntax to preserve the order!
>
> class foo(metaclass=OrderedDictBuilder):
> b = 1
> a = 2
>
> assert repr(foo) == "OrderedDict([('b', 1), ('a', 2)])"
>
> There is probably a way to get rid of the "metaclass=" part.
> I'm not sure to like it, though.
class OrderedDict(metaclass=OrderedDictBuilder):
pass
class foo(OrderedDict):
b = 1
a = 2
--
~Ethan~
More information about the Python-ideas
mailing list