0
var = "Old world"
class a(object):
    def b(self):
        print(var)
        #var = "Updated world"      
aObj = a()
aObj.b()

When I run the above code it works fine. But when i uncomment line 5 var="Updated World" it throws UnboundLocalError on line 4. I understand that i cannot modify var at line 5. But why I'm getting an error at line 4. Any good inputs are welcome.

  • Possible duplicate of [How to change a variable after it is already defined in Python](https://stackoverflow.com/questions/41369408/how-to-change-a-variable-after-it-is-already-defined-in-python) – Patrick Haugh Jun 04 '18 at 12:17
  • Python is in fact parsing and compiling the entire file before it executes even a single line of it. – deceze Jun 04 '18 at 12:20
  • @PatrickHaugh The question is different only the syntax matches. please try to understand it well. Thanks for replying soon. – Learner1947 Jun 04 '18 at 12:20
  • @Learner1947 I do understand it. As in the question I linked, you're trying to reference the value of a local variable before assigning it. When you remove the assignment line, then `var` never refers to a local variable, so it is determined to be a global variable instead. Did you read the answer to the question I linked? It explains why you are encountering this behavior. – Patrick Haugh Jun 04 '18 at 12:22

1 Answers1

0

The Python parser reads the entire file before executing even a single line of it. At the time a function is defined, its body is parsed and Python decides on what symbols (variable names) refer to what. If it sees any assignment statement inside the function, it takes the assignee to be a local variable; unless you explicitly override that with the global or nonlocal keywords. If there is no assignment statement in the function body, the variable is inherited from the outer scope.

deceze
  • 510,633
  • 85
  • 743
  • 889