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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With