- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How does variable scopes work in Python Modules?
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.
- How do Python modules work?
- How does Python while loop work?
- How does tuple comparison work in Python?
- How does mkdir -p work in Python?
- How does ++ and -- operators work in Python?
- How does garbage collection work in Python?
- How does class inheritance work in Python?
- How does issubclass() function work in Python?
- How does isinstance() function work in Python?
- How does Overloading Operators work in Python?
- How does Python dictionary keys() Method work?
- How does [d+] regular expression work in Python?
- How does B regular expression work in Python?
- How does * operator work on list in Python?