[prev in list] [next in list] [prev in thread] [next in thread]
List: python-bugs-list
Subject: [issue37728] 'is' behaving differently in script and interactive shel
From: Eryk Sun <report () bugs ! python ! org>
Date: 2019-07-31 9:12:48
Message-ID: 1564564368.91.0.145672641602.issue37728 () roundup ! psfhosted ! org
[Download RAW message or body]
Eryk Sun <eryksun@gmail.com> added the comment:
The CPython interpreter doesn't centrally cache and reuse float objects, and even if \
it did that would be an implementation detail, like what it does with small int \
objects and strings.
What you're seeing at the module level is a compilation side effect. The compiler is \
free to reuse immutable constants in a code object. For example:
>>> code = compile('af=1.1\nbf=1.1', '', 'exec')
>>> dis.dis(code)
1 0 LOAD_CONST 0 (1.1)
2 STORE_NAME 0 (af)
2 4 LOAD_CONST 0 (1.1)
6 STORE_NAME 1 (bf)
8 LOAD_CONST 1 (None)
10 RETURN_VALUE
In the above case, both af and bf are initialized with the same `1.1` constant float \
object, which is at index 0 of the code object's tuple of constants:
>>> code.co_consts
(1.1, None)
But if we run `af=1.1` and `bf=1.1` as separate statements in the REPL shell, the \
statements are compiled separately, and af and bf won't necessarily reference the \
same float object.
Don't expect two immutable objects that have the same value to be the same object -- \
unless it's a singleton such as `None` and `Ellipsis`:
>>> type(None)() is None
True
>>> type(Ellipsis)() is Ellipsis
True
Or an n-way extension of this case, such as bool in Python 3:
>>> bool(0) is False
True
>>> bool(1) is True
True
The consequences of immutability on object identity are discussed briefly in the \
final paragraph of "3.1 Objects, values, and types" [1]. Offhand, I don't know where \
the specific implementation details of CPython builtin immutable types and compiler \
behavior are discussed, if it's discussed at all.
[1] https://docs.python.org/3/reference/datamodel.html#objects-values-and-types
----------
nosy: +eryksun
resolution: -> not a bug
stage: -> resolved
status: open -> closed
_______________________________________
Python tracker <report@bugs.python.org>
<https://bugs.python.org/issue37728>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/python-bugs-list%40marc.info
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic