Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The scope of if __name__ == __main__

Tags:

python

scope

What is the scope of if __name__ == __main__? Is everything covered by this statement in global space ?

like image 490
Cemre Mengü Avatar asked Oct 09 '12 19:10

Cemre Mengü


4 Answers

There is nothing special about if __name__ == '__main__' block whatsoever. That is to say, its scope is determined by the place it occurs. Since such blocks typically occur at top-level, their scope is global.

If this block were to occur in a function, which is perfectly legal, its scope would be local—except that __name__ would still resolve to the global value defined in the module.

like image 170
user4815162342 Avatar answered Sep 28 '22 05:09

user4815162342


>>> if __name__ == '__main__':
...     x = 1
... print 'x' in globals()
True

edit: user4815162342 makes the excellent point that this if-statement can be written in any scope. It's most often written in the global scope.

Here it is inside a function:

>>> def foo():
...     if __name__ == '__main__':
...         bar = 1
... foo()
... print 'bar' in globals()
False
like image 40
Steven Rumbalski Avatar answered Sep 28 '22 04:09

Steven Rumbalski


Python doesn't have block-local scope, so any variables you use inside an if block will be added to the closest enclosing "real" scope. (For an if..main block, they'll usually be attributes of the module.)

like image 36
millimoose Avatar answered Sep 28 '22 06:09

millimoose


It is in the global scope as long as:

  1. it is called in the global scope, i.e. not from within a function
  2. it is in the code file that is being executed.

To illustrate (2):

Suppose you're code is in foo.py, and in bar.py, you have the statement from foo import *. In this case, the if __name__ == "__main__": block in foo.py is not executed. This block is only executed when foo.py is run

like image 31
inspectorG4dget Avatar answered Sep 28 '22 06:09

inspectorG4dget