On Sun, Mar 06, 2016 at 01:03:01AM -0600, boB Stepp wrote:

> Under the hood, are the two approaches above done in the same way?

Probably not, but the true answer will surely depend on which 
implementation and version of Python we are talking about.

When you run Python code, there are a number of separate stages that the 
interpreter/compiler may potentially perform:

- lexing and parsing: this is when the interpreter reads the source
  code and generates "tokens" for futher processing;

- the tokens may be then arranged into a parse tree;

- which is usually just a temporary intermediate representation prior
  to being arranged into an abstract syntax tree (which is much easier
  to process);

- the AST is then processed into byte-code for the Python virtual 
  machine (or, in principle, machine-code for a real machine);

- finally the virtual machine executes the byte-code, creating
  any objects need to be created and processing them.


In principle, either implicit or explicit concatenation could be 
performed at *any* of these stages, so long as it is performed.

My *guess* is that any Python implementation will perform implicit 
concatenation during the parsing and lexing stage, because it doesn't 
make sense to delay it later.

On the other hand, explicit concatenation with a plus sign is more 
likely to be done at the AST level, or possibly even later. Or not 
optimized at all.


> I
> get your semantics point, but are there two string objects created in
> both approaches or does the first in fact create only a single object?
>  If the first truly only creates a single object, then it seems that
> this is a more efficient approach.

In practical terms, in CPython today, there is no difference between the 
two, or if there is any difference, it's undetectible: by the time the 
compiler has generated the byte-code, the concatenation has been 
performed:

py> import dis
py> code = compile("""
... a = 'ab' 'cd'
... b = 'ab' + 'cd'
... """, "", "exec")
py> dis.dis(code)
  2           0 LOAD_CONST               0 ('abcd')
              3 STORE_NAME               0 (a)

  3           6 LOAD_CONST               4 ('abcd')
              9 STORE_NAME               1 (b)
             12 LOAD_CONST               3 (None)
             15 RETURN_VALUE


This may not apply to future versions, or other implementations.



-- 
Steve
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to