Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I don't understand your first argument at all. Why wouldn't the compiler know what the standard `range()` function does? The second one only makes sense since we aren't type hinting, however that too could be reversed by analyzing the code.

I'm sure it knows what the standard range() function does. It just doesn't know that that's the standard range function you use when the code is being run. Any Python program is also a module. Any module can be imported. Any imported module's global namespace is unknown at the time you write the program.

Imagine I have your code, above, in a module called nextlevelwizard, and I write my own little progam as this:

    import builtins
    def myrange(n):
        cur = 0
        while cur < n:
            print(cur)
            yield cur
            cur += 1
    builtins.range = myrange
    import nextlevelwizard
Now, suddenly, your loop has a side effect. Side effects cannot be "optimized away" - the whole point of programs are generally to produce some sort of side effect!

This is a silly example, of course, but the dynamic nature of Python means that it really is very hard to skip steps you assume are irrelevant.



Expect the compiler should import whatever module you are using and analyze that module's code just like in any compiled language.

Even in the example you gave it could replace the loop with a bunch of print calls since the result (yields) do nothing.

Compilers are hard.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: