This is a weird behavior.
Try this :
rep_i=0
print "rep_i is" , rep_i
def test():
global rep_i #without Global this gives error but list , dict , and others don't
if rep_i==0:
print "Testing Integer %s" % rep_i
rep_i=1
return "Done"
rep_lst=[1,2,3]
def test2():
if rep_lst[0]==1:
print "Testing List %s" % rep_lst
return "Done"
if __name__=="__main__":
test()
test2()
Why list do not need to declare global? are they automatically global?
I find it really weird, I use list most of the time and I don’t even use global at all to us them as global…
It isn’t automatically global.
However, there’s a difference between
rep_i=1andrep_lst[0]=1– the former rebinds the namerep_i, soglobalis needed to prevent creation of a local slot of the same name. In the latter case, you’re just modifying an existing, global object, which is found by regular name lookup (changing a list entry is like calling a member function on the list, it’s not a name rebinding).To test it out, try assigning
rep_lst=[]intest2(i.e. set it to a fresh list). Unless you declarerep_lstglobal, the effects won’t be visible outsidetest2because a local slot of the same name is created and shadows the global slot.