Python was designed (was Re: Multi-threading in Python vs Java)

Chris Angelico rosuav at gmail.com
Mon Oct 14 21:48:30 EDT 2013


On Tue, Oct 15, 2013 at 12:31 PM, Mark Janssen
<dreamingforward at gmail.com> wrote:
>> Python objects have dynamic operations suited
>> to a naive interpreter like CPython.
>
> Naive, no.
>

"Naive", in this instance, means executing code exactly as written,
without optimizing things (and it's not an insult, btw). For instance,
a C compiler might turn this into simple register operations:

int x=5;

int foo()
{
    x+=3;
    return x*2;
}

The two references to 'x' inside foo() can safely be assumed to be the
same 'x', and the value as written by the += MUST be the one used to
calculate *2. If you declare x to be volatile, that assumption won't
be made, and the interpretation will be naive. Now here's the CPython
equivalent:

x=5
def foo():
    global x
    x+=3
    return x*2

>>> dis.dis(foo)
  3           0 LOAD_GLOBAL              0 (x)
              3 LOAD_CONST               1 (3)
              6 INPLACE_ADD
              7 STORE_GLOBAL             0 (x)

  4          10 LOAD_GLOBAL              0 (x)
             13 LOAD_CONST               2 (2)
             16 BINARY_MULTIPLY
             17 RETURN_VALUE

Note that the global is stored, then reloaded. This is the naive
approach, assuming nothing about the relations between operations.
It's an easy way to be thread-safe, it just costs performance.

ChrisA



More information about the Python-list mailing list