Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value. [6.2.2. Literals][1]
I need to understand this passage above but find it uneasy. I need your help to clarify certain things:
>>> " Got any rivers you think are uncrossable ?" #1
' Got any rivers you think are uncrossable ?' #2
>>> " Got any rivers you think are uncrossable ?" #3
' Got any rivers you think are uncrossable ?' #4
#1 and #3 are two literals with the same value that obtain the same objects #2 and #4 respectively. The value of these objects is the same. How could their evaluation obtain different objects with the same value? What has occurrence to do with the result of evaluation here?
either the same occurrence in the program text or a different occurrence
How to distinguish between the same occurrence and a different occurrence ? And what has the place of occurrence to with the result of evaluation ?
CodePudding user response:
Compare these two:
>>> a = 'a'
>>> b = 'a'
>>> id(a)
1799740566768
>>> id(b)
1799740566768
vs
>>> a = 'a b'
>>> b = 'a b'
>>> id(a)
1799740710960
>>> id(b)
1799751802672
Internally, in the first example, a
and b
both refer to the same object, while in the second, they refer to different objects.
This can have some unexpected results: in the first case, a is b -> True
but in the second, a is b -> False
.
Why does it matter?
As remarked in a comment, you likely shouldn't need to care. In the case of immutable literals, it should make no difference functionally whether your code refers to the same object, or different objects, when accessing 'identical' literals. But, in the case of mutable objects, it is definitely important to be aware of possible side-effects.
For more info, see e.g. Under which circumstances do equal strings share the same reference? and What does sys.intern() do and when should it be used?
CodePudding user response:
Both are string objects and have different ids even if the value is the same. E.g.:
>>> id("My string")
140140708077104
>>> id("My string")
140140708085936
>>> my_first_string = "Repeated value"
>>> my_second_string = "Repeated value"
>>> my_first_string == my_second_string
True
>>> id(my_first_string) == id(my_second_string)
False