Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__main__ and scoping in python

Tags:

python

scope

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?

like image 746
David Cournapeau Avatar asked Jan 23 '11 18:01

David Cournapeau


People also ask

What is __ main __ in Python?

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.

What is scoping in Python?

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.

What Does main () do in Python?

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.

What are the four scopes in Python?

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.


2 Answers

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
like image 142
Sven Marnach Avatar answered Oct 04 '22 14:10

Sven Marnach


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.

like image 21
Santiago Alessandri Avatar answered Oct 04 '22 14:10

Santiago Alessandri