What is the scope of if __name__ == __main__
? Is everything covered by this statement in global space ?
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.
>>> 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
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.)
It is in the global scope as long as:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With