why cannot assign to function call
mdw at distorted.org.uk
Thu Jan 8 20:13:38 CET 2009
Erik Max Francis <max at alcyone.com> wrote:
> Terry Reedy wrote:
> > >>> a='par'+'rot'
> > >>> b='parrot'
> > >>> a is b
> > True
> One exactly doesn't really say much. It's implementation dependent, and
> depends on the length of the string:
> >>> a = 'this is a much longer ' + 'parrot'
> >>> b = 'this is a much longer parrot'
> >>> a is b
That Terry's example works is due to constant folding in the bytecode
In : a = 'parrot'
In : a is 'par' + 'rot'
Fair enough. But build the string in a more complicated way:
In : b = 'par'
In : a is b + 'rot'
What's going on? In the first case, the compiler notices that both
operands to `+' are constants, and evaluates the concatenation at
compile-time. The resulting constant string is then interned if it's
Putting part of the string in a variable is enough to stymie this
optimization -- the same compiler gets used in functions which can't
assume that the variable will still have the same value as it does now.
The concatenation method on strings doesn't try to intern the result, as
that might be a runtime performance loss.
> In practice, tests like these are pretty much never useful. It's
> completely implementation dependent when and under what circumstances
> fundamental immutable objects are reused, and it's not useful anyway;
> what you care about is whether two objects are equal or not, not whether
> they're the same object through some optimization behind the scenes.
Absolutely. The examples above provide insight into how the specific
implementation actually behaves; but that's of strictly academic
interest. (Well, I find that sort of thing interesting, anyway.)
More information about the Python-list