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?
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
In Python, the concept of scope is closely related to the concept of the namespace. As you've learned so far, a Python scope determines where in your program a name is visible. Python scopes are implemented as dictionaries that map names to objects. These dictionaries are commonly called namespaces.
The main function in Python acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.
You will learn about the four different scopes with the help of examples: local, enclosing, global, and built-in. These scopes together form the basis for the LEGB rule used by the Python interpreter when working with variables.
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
The thing here is that:
if __name__ == "__main__": foo = "bar"
defines a global variable named foo in that script. so any function of that module will have access to it.
The piece of code listed above is global to the module and not inside any function.
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