Compile time evaluation of dictionaries
Jean-Michel Pichavant
jeanmichel at sequans.com
Mon Mar 14 06:58:47 EDT 2011
Gerald Britton wrote:
> 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
>
>
>
>
1/ because no one would ever see the difference.
2/ immutables can always be evaluated before any high CPU consuming loop
3/ it would make the implementation more complex (i.e. more work for our
beloved active community) for no gain
4/ you can write C code to speed up things:
http://docs.python.org/extending/extending.html, when really needed.
JM
More information about the Python-list
mailing list