pythondebugginginterpreter

How to prove that 'a' 'b' are not automatically concatenated in python shell?


According to this article: Code Like a Pythonista: Idiomatic Python

There is a line that states:

"That's because this automatic concatenation is a feature of the Python parser/compiler, not the interpreter. You must use the "+" operator to concatenate strings at run time."

I do not understand this statement because I don't know how the python compiler or interpreter actually work. How does concatenation work? Because:

>>> a = 'three'
>>> b = 'four'
>>> a b

Will not evaluate to:

>>> a = 'three'
>>> b = 'four'
>>> a b
>>> 'three' 'four'
>>> 'threefour'

Are there any tools that will allow me to track the compilation process that starts from the raw text '*.py' until the output is printed out from the terminal?


Solution

  • This statement does not refer to the Python shell. In fact, both interactive input and file input behave virtually identically in this regard: In both,

    When you input Python source code, regardless of how exactly you do that, it is first compiled to bytecode. This compilation step accepts string literals without anything in between and treats it as a single string literal made out of those shorter literals. It then creates the exact same bytecode as if that single concatenated string was written, and when the interpreter executes that code it neither can nor needs to know that, in the source code, you wrote two string literals instead of one.