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?
__main__
. There's anif
that happens to compare a variable that happens to be called__name__
to something that happens to be the string literal"__main__"
.__main__
is a module, and each module has an associated scope. Tryimport __main__; type(__main__)
in the interpreter (not in IPython).if
introduces a new scope - which would be a more pressing issue. (Admittedly, "There is no scope__main__
is misleading, strictly speaking)