0

Recently I caught a bug in my code which wondered me enough. The main problem is that the code below works:

def test():
    print(memory)


if __name__ == "__main__":
    memory = 1
    test()

It would be clear if memory were defined at the top of file but this seems like breaking all the scope rules for me. However there must be some reason.

Long Smith
  • 1,339
  • 3
  • 21
  • 40
  • Seems logical to me. by the time `test()` is called, `memory` is already defined. – ifconfig Sep 05 '17 at 03:44
  • 1
    Python executes your program in order it reads it. When yiu define a function, it's executed only when you call it, so Python doesn't even look inside on the first run. You might as well assume that it replaces your call to 'test()' with the content of that function itself – avloss Sep 05 '17 at 03:46
  • @ifconfig Logical after what experience? I mean I used to use C and code which uses global variable in function before declaring does not compile. And this is for me seems logical. – Long Smith Sep 05 '17 at 03:48
  • You meant to say illogical, right? Python has some interesting scope rules from what I can gather. – ifconfig Sep 05 '17 at 03:49
  • @avloss Thanks. Think I should get deeper in how python works. If you post your comment as an answer I will accept it. – Long Smith Sep 05 '17 at 03:53
  • 1
    @ifconfig Yes, it has. However even my code checker usually gives me an error about using variables before assignment but sometimes it just ignores all the problems(some vim bug I believe). – Long Smith Sep 05 '17 at 03:57
  • It isn't good practice, yes, but it just works that way.. – ifconfig Sep 05 '17 at 03:57
  • Relevant answer: https://stackoverflow.com/a/293097/4110233 – TheChetan Sep 05 '17 at 04:00
  • https://docs.python.org/3/reference/executionmodel.html#resolution-of-names – wwii Sep 05 '17 at 04:02
  • 2
    @avloss: Not quite. It compiles all the code in the function `test` before `if __name__ == '__main__':`, but doesn't resolve the name referred to by `memory` until the function is called, at which point it follows scope rules for resolution. – Steven Rumbalski Sep 05 '17 at 04:04

1 Answers1

0

Even though the working of memory variable seems strange, it is expected. The Variable Scope is not breached!

if __name__ == "__main__": - This statement is used for defining or declaring global functionality when the source file is called directly for execution rather than imported to another file and called from a third module.

Thus when you directly execute the source file, it will first define the variable - memory, to be global and can be accessed in function test as a global variable(no overshadowing happening).

Refer the below link for more understanding - What does if __name__ == "__main__": do?

Karan Chopra
  • 174
  • 8