Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to have python dict literals evaluated as ordered dicts?

Disclaimer: Yes I realize what I'm suggesting is crazy, I have a very special (ab)use case.

Within a particular exec I want dictionary literals to evaluate to ordered dictionaries, so I can preserve the original ordering from the exec'd code.

I tried replacing __builtin__.dict before the exec (being very careful to restore it after), however that doesn't affect dict literals, only the dict call itself.

>>> import __builtin__
>>> __builtin__.dict = list
>>> exec "a={}"
>>> a
{}
>>> exec "a=dict()"
>>> a
[]

Obviously there is the dis module, but that's the nuke the site from orbit approach.

Is there some other way I can hook into the evaluation of dict literals and change what happens?

P.S. for Python2.6

like image 414
Gordon Wrigley Avatar asked Nov 13 '22 08:11

Gordon Wrigley


1 Answers

I'd suggest to have a look at the ast module, with which you could ast.parse the given code and replace every ast.Dict entry with the corresponding constructor call.

(But, sorry, it seems that you want something really strange.)

like image 91
bereal Avatar answered Dec 28 '22 09:12

bereal