If I have an expression that I wish to evaluate in Python, such as the expression for r
in the code snippet below, will the Python interpreter be smart and reuse the subresult x+y+z
, or just evaluate it twice?
Which Python interpreter are you talking about? There are currently four production-ready, stable Python implementations in widespread use. None of those actually have a Python interpreter, every single one of them compiles Python.
Some of them may or may not be able to perform this optimization for at least some programs under at least some circumstances.
The Python Language Specification does neither require nor forbid this kind of optimization, so any specification-conforming Python implementation would be allowed to, but not required, to perform this optimization.
I am pretty certain that, contrary to all the other answers which state that Python cannot do this, PyPy is capable of performing this optimization. Also, depending on which underlying platform you use, code executed using Jython or IronPython will also benefit from this optimization, e.g. I am 100% certain that the C2 compiler of Oracle HotSpot does perform this optimization.
I'd also be interested to know if the answer to this question would be the same for a compiled language […].
There is no such thing as a "compiled language". Compilation and interpretation are traits of the compiler or interpreter (duh!) not the language. Every language can be implemented by a compiler, and every language can be implemented by an interpreter. Case in point: there are interpreters for C, and conversely, every currently existing production-ready, stable, widely-used implementation of Python, ECMAScript, Ruby, and PHP has at least one compiler, many even have more than one (e.g. PyPy, V8, SpiderMonkey, Squirrelfish Extreme, Chakra).
A language is an abstract set of mathematical rules and restrictions written on a piece of paper. A language is neither compiled nor interpreted, a language just is. Those concepts live on different layers of abstraction; if English were a typed language, the term "compiled language" would be a type error.
I'd also be interested to know if the answer to this question would be the same for […] e.g. C.
There are many production-ready, stable C implementations in widespread use. Some of them may or may not be able to perform this optimization for at least some programs under at least some circumstances.
The C Language Specification does neither require nor forbid this kind of optimization, so any specification-conforming C implementation would be allowed to, but not required, to perform this optimization.