I was somehow surprised by the following behavior:
def main():
print "%s" % foo
if __name__ == "__main__":
foo = "bar"
main()
i.e. a module function has access to enclosing variables in the __main__. What's the explanation for it?
Variables in the current modules global scope are visible everywhere in the module -- this rule also holds for the __main__ module.
From Guido's tutorial:
At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:
- the innermost scope, which is searched first, contains the local names
- the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
- the next-to-last scope contains the current module’s global names
- the outermost scope (searched last) is the namespace containing built-in names
__main__. There's anifthat happens to compare a variable that happens to be called__name__to something that happens to be the string literal"__main__". - user395760__main__is a module, and each module has an associated scope. Tryimport __main__; type(__main__)in the interpreter (not in IPython). - Sven Marnachifintroduces a new scope - which would be a more pressing issue. (Admittedly, "There is no scope__main__is misleading, strictly speaking) - user395760