Compile time evaluation of dictionaries
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Mar 10 19:15:56 EST 2011
On Thu, 10 Mar 2011 17:40:40 -0500, Terry Reedy wrote:
> On 3/10/2011 11:23 AM, 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:
>
> In fact, it could be evaluated at writing time ;-).
True, but why do stuff when the compiler can do it for you? Any constant
folding could be done at writing time, but readability and maintenance
dictates that we write something like:
C = 1.0/7
rather than
C = 0.14285714285714285
> This would be an
> example of constant folding, except that a dict is not, in itself, a
> constant.
Nevertheless, since the dict only exists for a single operation, it might
as well be a constant. In general, Python can't safely make many
assumptions about compile-time behaviour, since nearly anything can be
modified at run-time, but the behaviour of built-in literals is one thing
that can't change.
I don't see any reason why Python couldn't optimize the above at compile-
time, and I can only think of two reasons why it won't:
- lack of interest from anyone willing and able to write a patch;
- the added complexity may be more than the benefit gained.
--
Steven
More information about the Python-list
mailing list