About the implementation of del in Python 3

Random832 random832 at fastmail.com
Fri Jul 7 12:14:26 EDT 2017


On Fri, Jul 7, 2017, at 10:41, Nathan Ernst 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

Equal constants are combined (into a single object in the code object's
constant list - the compiler actually uses a dictionary internally) at
compile time, when you execute two separate lines in the interactive
interpreter they are compiled separately.

I would call your first case multiple statements on a line, not multiple
expressions in one statement. But what's important is the separate lines
of the interactive interpreter and therefore separate compile contexts -
if you were to do exec('n=4000\nm=4000') you would get a single object.

With a sufficiently small number (between 0 and 256 inclusive), they are
globally cached and you will get the same object even across separate
compilations, because the compiler gets the same object when it parses
"10" in the first place.

Imagine more or less, this process:

d = {}
a = int("4000")
if a in d: i = d[a]
else: i = d[a] = len(d)
b = int("4000")
if b in d: j =d[b]
else: j = d[b] = len(d)
c = d.keys()
n = c[i]
m = c[j]

When you do it on two separate prompts you get:

d = {}
a = int("4000")
if a in d: i = d[a]
else: i = d[a] = len(d)
c = d.keys()
n = c[i]

d = {}
a = int("4000")
if a in d: i = d[a]
else: i = d[a] = len(d)
c = d.keys()
m = c[i]



More information about the Python-list mailing list