2

I am seeing an error when assigning either a global or an enclosing-function local to a local variable with the same name. The code below illustrates this issue, where f() runs fine, while g() raises an error. It seems like python knows that a is being assigned locally, so it says that all references to a are now local, even the references before a is actually assigned locally. What explains this behavior? I am running Python 2.7.12 :: Anaconda 4.2.0 (64-bit).

In [18]: a = 1
    ...: 
    ...: def f():
    ...:   x = a
    ...:   print x
    ...: 
    ...: def g():
    ...:   a = a
    ...:   print a
    ...:   

In [19]: f()
1

In [20]: g()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-20-d65ffd94a45c> in <module>()
----> 1 g()

<ipython-input-18-f3d970bdaa2b> in g()
      6 
      7 def g():
----> 8   a = a
      9   print a
     10 

UnboundLocalError: local variable 'a' referenced before assignment
andrew
  • 2,524
  • 2
  • 24
  • 36
  • 1
    Always Function has scopes and bound to its variable.[refer this link](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – Veera Balla Deva Jan 21 '18 at 15:34
  • I see no scoping issues here. When `a` is first referenced, there are no local definitions of `a`, so in the answer you referenced it should move on to the locally-enclosed variables and then global variables, where `a` lives. – andrew Jan 21 '18 at 15:43

1 Answers1

3

The short answer is that, within g(), you need to declare

global a

if you want to be able to modify "a" from within a function and have this effect globally visible. However, in your case, the effect of using "a" within g() is to convert this variable name to refer to a local-scope variable, which then hides the global "a" which you're attempting to use on the righthand side of your assignment, triggering the exception. This is more fully explained here. There is also a Python FAQ which explains the rules that make f() work without the need for the "global a".

rwp
  • 1,786
  • 2
  • 17
  • 28