I'm trying to understand what happens with assignment and the creation of new references to an object, or why I get a new created object when assigning.
I can't get my head on how Python and/or Sublime work here. I have this simple Sublime plugin:
import sublime
import sublime_plugin
class TestpythonCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
sel = view.sel()
sel_zero = sel[0];
sel_for = []
for r in sel:
sel_for.append(r)
sel_gen = [r for r in view.sel()]
print('SEL => ' + str(sel[0].a) +':' + str(sel[0].b) + ' ID: ' + str(id(sel[0])))
print(str(id(sel[0])) + ' .. ' + str(id(sel[0])) + ' .. access A value: ' + str(sel[0].a) + ' .. ' + str(id(sel[0])))
print('SEL[0] id is ' + str(id(sel[0])))
print('SEL_ZERO => ' + str(sel_zero.a) +':' + str(sel_zero.b) + ' ID: ' + str(id(sel_zero)))
print('SEL_FOR => ' + str(sel_for[0].a) +':' + str(sel_for[0].b) + ' ID: ' + str(id(sel_for[0])))
print('SEL_GEN => ' + str(sel_gen[0].a) +':' + str(sel_gen[0].b) + ' ID: ' + str(id(sel_gen[0])))
print('----- Test with self')
print(id(sel[0]) == id(sel[0]))
print(sel[0] is sel[0])
print(sel[0] == sel[0])
print('----- Test with list & generator function')
print(sel[0] is sel_zero)
print(sel[0] == sel_zero)
print(sel[0] is sel_for[0])
print(sel[0] == sel_for[0])
print(sel[0] is sel_gen[0])
print(sel[0] == sel_gen[0])
Executing this returns:
SEL => 657:657 ID: 4378999048
4378998328 .. 4378998328 .. access A value: 657 .. 4378998328
SEL[0] id is 4378998328
SEL_ZERO => 657:657 ID: 4379000488
SEL_FOR => 657:657 ID: 4378996816
SEL_GEN => 657:657 ID: 4378998760
----- Test with self
True
False
True
----- Test with list & generator function
False
True
False
True
False
True
Now, too many things don't make sense to me here:
- First print shows
sel[0]
id to be 4378999048, but printing it again gives another id (4378998328) - Third print does the same; looks the id printed in the first line is lost/changed/unused.
- First "Test with self" print makes sense (comparison of id strings is True); but I can't get the sense of the second print, using
is
(whysel[0] is not sel[0]
?).
I am trying to understand how stuff works here. Specifically, the purpose is to understand why I get new objects (instead of having a new reference to the same object) when using the generator-expression with for
.
I use SublimeText3 and Python 2.7.10.
EDIT: I'd be interested in the best practice for checking reference equality, without using is
(that seems to be inconsistent, depending on implementation and caching).