why cannot assign to function call

Mark Wooding 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
> False

That Terry's example works is due to constant folding in the bytecode
compiler.  Consider:

In [1]: a = 'parrot'

In [2]: a is 'par' + 'rot'
Out[2]: True

Fair enough.  But build the string in a more complicated way:

In [3]: b = 'par'

In [4]: a is b + 'rot'
Out[4]: False

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
short enough.

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.)

-- [mdw]

More information about the Python-list mailing list