Even though tuples are immutable, they are stored in different addresses in interactive mode. Why?
Asked Answered
E

2

8
t = (1,2,3)
t1 = (1,2,3)
print(id(t))
print(id(t1))

The above lines of code gives the same addresses in script mode in Python, but in interactive mode it outputs different addresses. Can anyone explain the reason for this?

Ecker answered 11/6, 2020 at 15:20 Comment(4)
There is never a guarantee in Python that immutable objects are stored in the same address per unique value.Luteolin
The compiler notices that the tuples are the same and combines them. The interactive REPL doesn't do this extra analysis.Whithersoever
@Luteolin - the exception being None which is guaranteed to be a singleton. foo is None is always safe. docs.python.org/3.8/c-api/none.html#the-none-objectLeatherback
Same goes for True, False and Ellipsis. What "no guarantees" really means in this context is that you're never guaranteed to get different object identities for immutable types when the values are the same.Equidistant
W
5

When the script is being compiled, the compiler can search for all the equivalent tuples and generate code to use the same reference for all of them.

But in interactive mode, it would need to keep a cache of all tuples so it could search for a previous equivalent tuple and return a reference to it, rather than creating a new tuple each time. The interactive interpreter doesn't do this.

If you assign both variables on the same line, you actually get the same tuple.

t = (1, 2, 3); t1 = (1, 2, 3)

This is presumably because it's running the compiler for each input, so it can do the full analysis and optimization.

Whithersoever answered 11/6, 2020 at 15:27 Comment(2)
It can do it, if you put both definitions on the same physical line, which the interactive interpreter can process as a whole: t = (1, 2, 3); t1 = (1, 2, 3).Blowtube
Thank you that was very helpful.Ecker
C
0

A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, a class definition

Meanwhile, each command typed interactively is a block.

That's because your first code is inside a code block(a module) and it executed as a unit. For example: In a script as a unit:

x = (1,2)

y = (1,2)

print(x is y) # result is True.

But in interactive shell , when you execute them in two different commands, they are in different code blocks. But in interactive mode:

>>> x = (1,2) # a unit

>>> y = (1,2) # a unit

>>> x is y # result is False

But in interactive mode we can use the fallowing commands:

>>> x,y = (1,2),(1,2) # a unit

>>> x is y # result is True
Curl answered 20/6, 2023 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.