why () is () and [] is [] work in other way?

Chris Angelico rosuav at gmail.com
Sat Apr 21 23:54:08 EDT 2012


On Sun, Apr 22, 2012 at 1:14 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> The CPython interpreter is especially aggressive in optimizing multiple
> literals in the same line. Compare this:
>
>>>> x = 3.1; y = 3.1; x is y
> True
>
> with this:
>
>>>> x = 3.1
>>>> y = 3.1
>>>> x is y
> False
>
>
> Again, this is an accident of implementation, and cannot be relied on.

That's the interactive interpreter, which works on a basis of lines.
With .py files, both 2.6 and 3.2 on Windows appear to do the same
optimization at module level. But either way, that's optimization of
constants.

>>> x=3.1+1.0; y=3.1+1.0; x is y
False
>>> x=3.1; y=3.1; x+y is x+y
False

Which can have micro-optimization implications:
>>> x=1048576; y=1048576; x is y
True
>>> x=1<<20; y=1<<20; x is y
False

But if you're concerning yourself with this kind of optimization,
you're probably wasting your time. :)

ChrisA



More information about the Python-list mailing list