optimization with the "compiler" module

Philip Swartzleonard starx at pacbell.net
Wed Apr 17 06:27:20 EDT 2002


Andrew Dalke || Tue 16 Apr 2002 04:35:54p:

> sean.bowman at acm.org:
>>I'm wondering if there's a way to optimize code generated using the
>>compiler module.  for example, if I say::
>>
>> import dis
>> from parser import compileast, expr
>>
>> code = compileast(expr('x+3+7.'))
>> print dis.dis(code)
>>
>>I notice that the constants aren't folded.  is there a way to do this, 
or
>>do I have to fiddle with the ast myself?
> 
> Suppose you have
> 
> class Strange:
>     def __add__(self, other):
>         return self
> x = Strange()
> 
> Then x+3+7.0 = (x+3)+7.0 = x+7.0 = x
> 
> The compiler can't know what 'x' might be so can't fold constants
> in this case.  You could if it was '3+7.0+x'.

In this case, wouldn't 3+7.0+x be a Typeerror or something? Int doesn't 
know how to add with a Strange, and Strange dosen't have an upgrading 
function... or do we assume addition is always commutitive and try '3+x+
7.0' (effectively), therefore breaking the optimization mentioned by the 
other... =)


-- 
Philip Sw "Starweaver" [rasx] :: www.rubydragon.com



More information about the Python-list mailing list