How does variable scopes work in Python Modules?

PythonServer Side ProgrammingProgramming

Namespace is a way to implement scope. In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. Think of it as an "evaluation context". When a function, etc., finishes execution, the namespace is dropped. The variables are dropped. Plus there's a global namespace that's used if the name isn't in the local namespace.

Variables are generally created only in a local namespace. The global and nonlocal statements can create variables in other than the local namespace.

Scope resolution is required when a variable is used to determine where should its value be come from. Scope resolution in Python follows the LEGB rule.

L, Local — Names assigned in any way within a function (or lambda), and not declared global in that function.

E, Enclosing-function locals — Name in the local scope of any and all statically enclosing functions(or lambdas), from inner to outer.

G, Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file.

B, Built-in (Python) — Names preassigned in the built-in names module : open, range,SyntaxError, etc.

Updated on 30-Jul-2019 22:30:20