Python and the need for speed

bartc bc at freeuk.com
Fri Apr 14 20:23:39 EDT 2017


On 15/04/2017 00:40, Rick Johnson wrote:
> On Wednesday, April 12, 2017 at 1:48:57 AM UTC-5, Steven D'Aprano wrote:

>>     answer = 0
>>     for i in range(10):
>>         answer += 1
>>
>> instead of
>>
>>     answer = 10
>>
>> So... how exactly does the compiler prohibit stupid code?
>
> Easy. The same way _any_ optimizer optimizes code, by
> analysing the code!

In Python, the optimising would need to be done every time you run from 
source. You can't spend too long at it. (I don't know how much it relies 
on caching pre-compiled byte-code.)

  In this example, the integer named
> 'answer` is simply being incremented in a superfluous loop.
> Nothing here is "dynamic".

In Python, nearly everything is.

  For example:
>
>   * `range(10)` will always produce a list of the _same_ 10
>   integers.

You don't know if 'range' is still a range. If this has been executed 
first, then the answer will be 20:

oldrange=range
def double(x): return oldrange(x*2)
range=double

>   * `for i in range(10)` will aways iterate over the _same_
>   10 integers

And range could be set to something else each time the loop is executed.


>   * `answer += 1` will always increment the "current integer
>   value" by 1

I don't know if it's possible to override __iadd__ for integers so that 
+=1 does something different here.

But if there is any code between answer=0 and the start of the loop, 
then there is the possibility that answer could be something different.

-- 
bartc



More information about the Python-list mailing list