About the implementation of del in Python 3

Ian Kelly ian.g.kelly at gmail.com
Fri Jul 7 12:28:03 EDT 2017


On Fri, Jul 7, 2017 at 8:41 AM, Nathan Ernst <nathan.ernst at gmail.com> wrote:
> Looks like single expression statements are handled a bit differently than
> multiple expression statements:
>
> Python 3.5.2 (default, Nov 17 2016, 17:05:23)
> [GCC 5.4.0 20160609] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> n = 4000; m = 4000; n is m
> True
>>>> n = 4000
>>>> m = 4000
>>>> n is m
> False

It actually has to do with units of compilation. In the first example,
all three statements are compiled together and the constants are
optimized to the same object. In the second example, because you're
testing this in the REPL they're compiled at different times and since
4000 is larger than what CPython will intern, you end up with
different objects.

If however, you take the second example and gather it into a function,
you'll get the compile-time optimization again:

>>> def f():
...     n = 4000
...     m = 4000
...     return n is m
...
>>> f()
True



More information about the Python-list mailing list