Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, why is list[] automatically global?

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...

like image 509
Phyo Arkar Lwin Avatar asked Jun 13 '11 10:06

Phyo Arkar Lwin


1 Answers

It isn't automatically global.

However, there's a difference between rep_i=1 and rep_lst[0]=1 - the former rebinds the name rep_i, so global is 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=[] in test2 (i.e. set it to a fresh list). Unless you declare rep_lst global, the effects won't be visible outside test2 because a local slot of the same name is created and shadows the global slot.

like image 92
Alexander Gessler Avatar answered Oct 02 '22 02:10

Alexander Gessler