0

Trying to plenny understand when a variable is treated as a "local variable" of a function, I made this toy example:

x = 100

def foo():
    temp = x + 1
    print(temp)
    #x = temp     # uncommenting this line will rise an error

foo()

If you keep x = temp commented, x will be a global variable, and the code will run ok. But, uncommenting that, x will be automatically treated as a local varialbe since the beginning of the function, althoug the write instruction is at the end (and despite that Python is an interpeter).

So is it correct?: "A variable is local of a function just if it's written anywhere inside the function?"

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Ali Rojas
  • 549
  • 1
  • 3
  • 12
  • 2
    Python isn't really an interpreter in the strictest VB6 sense of the word. It does some optimizations under the hood after parsing, but before executing the code. One of those optimizations is that it optimizes local lookups so they don't have to hit the scope's chained hash maps. If you `import dis` and then `dis.dis(foo)` you'll see that the working version uses `LOAD_GLOBAL 0 (x)` while the non-working version uses `LOAD_FAST 0 (x)`. Python saw that `x` was a local variable and then emitted _local_ lookups for all `x` lookups in the scope ... even if the variable was not defined yet. – Sean Vieira Jul 20 '21 at 23:45
  • 1
    Thanks @SeanVieira. And the short answear for my question seams to be "yes". – Ali Rojas Jul 21 '21 at 00:01
  • 2
    The answer is yes. This happens *at compile time*. Almost no modern languages are purely interpreted.gor the CPython runtime, Python source code is first compiled to byte code, which is then executed by the runtime interpreter. This is much like, say, Java – juanpa.arrivillaga Jul 21 '21 at 00:06
  • As an aside, in the future please always add a generic [python] tag to all python related questions. Use a version specific tag at your discretion. Note, at this point, Python 3 *is Python*. Python 2 is passed its official end of life – juanpa.arrivillaga Jul 21 '21 at 00:09

0 Answers0