Compile time evaluation of dictionaries

Gerald Britton gerald.britton at gmail.com
Thu Mar 10 17:23:32 CET 2011


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:

>>> dis(compile(
... '"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.

--
Gerald Britton



-- 
Gerald Britton



More information about the Python-list mailing list