0

I'm using Python2.7 and still quite confused about scoping in python. I can't explain why the situation can happen. Somebody could help me. Thanks in advance.

case 1:

x = 1
def func():
    print x

func()

=> result:

1

case 2:

x = 1
def func():
    print x
    x = 9
func()

=> result:

UnboundLocalError: local variable 'x' referenced before assignment

When I add the line x = 9 in case 2, an error occurred.

awesoon
  • 32,469
  • 11
  • 74
  • 99
nguyenngoc101
  • 1,211
  • 4
  • 16
  • 28
  • Please have a look here: http://stackoverflow.com/questions/17142544/python-single-integer-variable-between-function/17142816#17142816 I don't know how to mark the dupicate thing : – enpenax Jun 19 '13 at 11:31
  • @user2033511: You don't have enough reputation to do it, but no worries; you did the next best thing. – John Y Jun 19 '13 at 11:36

1 Answers1

1

In case you reassign an external variable in a method, you should use global :

x = 1
def func():
    global x
    print x
    x = 9
func()

In case of mutable variables ( like list or dict ) when you just need to modify the internal state ( list.append, list.pop ) - you don't need global keyword.

StKiller
  • 7,631
  • 10
  • 43
  • 56
  • 1
    Immutability has **nothing** to do with it. Variable assignment (`x = ...`) *always* behaves this way (i.e. creates a new local). Some operations only possible on mutable objects, such as item assignment (`x[0] = ...`), work differently but that shouldn't come as a surprise as they are different operations. –  Jun 19 '13 at 11:42
  • In this case I see an int as immutable and a list/dict as mutable type. May be the naming is not 100% precise in this case, but it describes well the situation, imho. – StKiller Jun 19 '13 at 11:47
  • Your examples of mutable and immutable are basically correct, what I'm saying is that it doesn't matter whether the objects involved are mutable. That is, the qualification "is immutable" is pointless, confusing and overly restrictive. OP would get the exact same error regardless of what objects are assigned to `x` inside and outside of `func` (try it -- the 1 and the 9 with arbitrary mutable objects). –  Jun 19 '13 at 11:49
  • Got you point, will edit the answer. – StKiller Jun 19 '13 at 11:51