[Python-ideas] Let's be more orderly!
Amaury Forgeot d'Arc
amauryfa at gmail.com
Wed May 15 18:27:46 CEST 2013
2013/5/15 Don Spaulding <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.
--
Amaury Forgeot d'Arc
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130515/11282bf1/attachment-0001.html>
More information about the Python-ideas
mailing list