Why doesn't Python optimize away temporary variables?

徘徊边缘 提交于 2019-12-05 16:49:21

Because Python is a highly dynamic language, and references can influence behaviour.

Compare the following, for example:

>>> id(object()) == id(object())
True
>>> ob1 = object()
>>> ob2 = object()
>>> id(ob1) == id(ob2)
False

Had Python 'optimised' the ob1 and ob2 variables away, behaviour would have changed.

Python object lifetime is governed by reference counts. Add weak references into the mix plus threading, and you'll see that optimising away variables (even local ones) can lead to undesirable behaviour changes.

Besides, in Python, removing those variables would hardly have changed anything from a performance perspective. The local namespace is already highly optimised (values are looked up by index in an array); if you are worried about the speed of dereferencing local variables, you are using the wrong programming language for that time critical section of your project.

Issue 2181 (optimize out local variables at end of function) has some interesting points:

  • It can make debugging harder since the symbols no longer exist. Guido says only do it for -O.
  • Might break some usages of inspect or sys._getframe().
  • Changes the lifetime of objects. For example myfunc in the following example might fail after optimization because at the moment Python guarantees that the file object is not closed before the function exits. (bad style, but still)

    def myfunc():
        f = open('somewhere', 'r')
        fd = f.fileno()
        return os.fstat(fd)
    

    cannot be rewritten as:

    def bogus():
        fd = open('somewhere', 'r').fileno()
        # the file is auto-closed here and fd becomes invalid
        return os.fstat(fd)
    
  • A core developer says that "it is unlikely to give any speedup in real-world code, I don't think we should add complexity to the compiler."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!