1

In below code a and b are having same ids

>>> a,b=470,470
>>> id(a)
32404032
>>> id(b)
32404032

but not here,

>>> a = 470
>>> b = 470
>>> id(a)
32403864
>>> id(b)
32344636

And also if same list objects are created in same line then giving different ids

>>> a,b=[1,2], [1,2]
>>> id(a)
32086056
>>> id(b)
32653960
>>>

Why variables with same integers created on same line have same ids but not when created on different lines, this is also different with lists.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Rajesh
  • 39
  • 4

1 Answers1

2

Yes, for immutable objects the compiler will create constants and re-use them. You can't do this for mutable objects like lists however, because then you'd be manipulating the same object if you made changes via one reference or another.

You can extract the constants by looking at the co_consts attribute of a code object; the easiest way to get one of those is to use the compile() function:

>>> compile("a,b=470,470", '', 'single').co_consts
(470, None, (470, 470))

In the interactive interpreter, separate lines are compiled separately, so have separate constants. In a separate Python script, each scope has their own constants allowing for wider sharing. In the interactive interpreter, create a function or class to get a separate scope with their own constants:

>>> def foo():
...     a = 470
...     b = 470
...     return id(a) == id(b)
...
>>> foo()
True
>>> foo_code = compile('''\
... def foo():
...     a = 470
...     b = 470
...     return id(a) == id(b)
... ''', '', 'single')
>>> foo_code = compile('''
... def foo():
...     a = 470
...     b = 470
...     return id(a) == id(b)
... ''', '', 'single')
>>> foo_code.co_consts
(<code object foo at 0x1018787b0, file "", line 2>, None)
>>> foo_code.co_consts[0].co_consts  # constants for the foo function code object
(None, 470)

These are implementation details (optimisations), you should not rely on them.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343