Unexpected string behaviour: txt = 'this' ' works'

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Feb 11 19:57:34 EST 2009


On Wed, 11 Feb 2009 12:57:31 -0800, bearophileHUGS wrote:

> Jason:
>> It's such a minor optimization, that you probably wouldn't see any
>> effect on your program.
> 
>>>> from dis import dis
>>>> def f():
> ...  return 'This is ' + 'an example.' ...
>>>> dis(f)
>   2           0 LOAD_CONST               3 ('This is an example.')
>               3 RETURN_VALUE


That's a feature of the CPython keyhole optimizer, not a language 
feature. I expect that if you try that same thing in various other 
Pythons (and earlier versions of CPython) you'll get a different result. 
And like all optimizations, it's not a language feature, it's subject to 
removal without notice if necessary.

If you want guaranteed implicit concatenation, you need to leave out the 
plus operator. That is a language feature.

And I do call it a feature. I find it useful, and I've never run into any 
bugs caused by it, and if I did, I expect they would show up quickly:

x = "foo", "bar"
y = "foo" "bar"

x is a tuple of length 2, y is a string of length 6. You'll soon notice 
the difference. Since it only effects literals, it should be easy enough 
to find.




-- 
Steven



More information about the Python-list mailing list