> From: "Cesare Di Mauro" <cesare.dima...@a-tono.com> > So if Python will generate > > LOAD_CONST 1 > LOAD_CONST 2 > BINARY_ADD > > the constant folding code will simply replace them with a single > > LOAD_CONST 3 > > When working with such kind of optimizations, the temptation is to > apply them at any situation possible. For example, in other languages > this > > a = b * 2 * 3 > > will be replaced by > > a = b * 6 > > In Python I can't do that, because b can be an object which overloaded > the * operator, so it *must* be called two times, one for 2 and one for 3.
Not necessarily. For example C/C++ doesn't define the order of the operations inside an expression (and AFAIK neither Python) and therefore folding 2 * 3 is OK whether b is an integer or an arbitrary object with mul operator overloaded. Moreover one would expect * to be associative and commutative (take a look at Python strings); if a * 2 * 3 returns a different result from a * 6 I will find it very surprising and probably reject such code. However you can fix the order of operations like this: a = (b * 2) * 3 or a = b * (2 * 3) or a = b * 2 a = a * 3 -- Alexandru Moșoi http://alexandru.mosoi.googlepages.com _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com