- 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
Explain python namespace and scope of a variable.
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.
Each variable name is checked in the local namespace (the body of the function, the module, etc.), and then checked in the global 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.
- Explain scope of a variable in C language.
- Explain variable / Array scope in PowerShell function.
- PHP Variable Scope
- How variable scope works in Python function?
- Extending namespace and Unnamed namespace
- Namespaces and Scope in Python
- What is the scope of a private member variable of a class in C#?
- What is the scope of a protected member variable of a class in C#?
- What is the scope of a public member variable of a class in C#?
- What is the scope of an internal variable of a class in C#?
- What is a namespace in Python?
- Explain Binding of a variable in C language.
- Explain Lifetime of a variable in C language.