Compile time evaluation of dictionaries

G

Gerald Britton

Today I noticed that an expression like this:

"one:%(one)s two:%(two)s" % {"one": "is the loneliest number", "two":
"can be as bad as one"}

could be evaluated at compile time, but is not:
.... '"one:%(one)s two:%(two)s" % {"one": "is the loneliest number",
"two": "can be as bad as one"}',
.... '','exec'))
 1           0 LOAD_CONST               0 ('one:%(one)s two:%(two)s')
             3 BUILD_MAP                2
             6 LOAD_CONST               1 ('is the loneliest number')
             9 LOAD_CONST               2 ('one')
            12 STORE_MAP
            13 LOAD_CONST               3 ('can be as bad as one')
            16 LOAD_CONST               4 ('two')
            19 STORE_MAP
            20 BINARY_MODULO
            21 POP_TOP
            22 LOAD_CONST               5 (None)
            25 RETURN_VALUE
Any idea why Python works this way?  I see that, in 3.2, an
optimization was done for sets (See "Optimizations" at
http://docs.python.org/py3k/whatsnew/3.2.html) though I do not see
anything similar for dictionaries.
 
J

John Nagle

Today I noticed that an expression like this:

"one:%(one)s two:%(two)s" % {"one": "is the loneliest number", "two":
"can be as bad as one"}

could be evaluated at compile time, but is not:

CPython barely evaluates anything at compile time.

John Nagle
 
S

Steven D'Aprano

Today I noticed that an expression like this:

"one:%(one)s two:%(two)s" % {"one": "is the loneliest number", "two":
"can be as bad as one"}

could be evaluated at compile time, but is not: [...]
Any idea why Python works this way?  I see that, in 3.2, an optimization
was done for sets (See "Optimizations" at
http://docs.python.org/py3k/whatsnew/3.2.html) though I do not see
anything similar for dictionaries.

Python is a language, what you are looking at is an implementation of
that language. Although I have never used it myself, apparently Cesare Di
Mauro's WPython does more constant folding optimizations than CPython.
See pages 21-24 of

http://wpython2.googlecode.com/files/Beyond Bytecode - A Wordcode-based Python.pdf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top