Scope

1. Explain namespaces.
A namespace is a container that holds a set of identifiers (names) and the corresponding objects.
2. What is the namespace used for?
It serves as a mapping between names and objects, allowing you to access variables, functions, classes, and other objects by their names. Namespaces help organize and manage the scope and visibility of identifiers in a program.
3. Explain local (Function) namespace(scope).
The local namespace contains local variables and parameters defined within that function.
4. When will a new local scope be created?
A new local scope will be created every time the function is called.
5. Explain global (Module) namespace(scope).
The global namespace includes names defined at the top level of a script or module. Names in this Python scope are visible from everywhere in your code in that particular script.
6. Explain built-in namespace(scope).
The built-in namespace contains the names of Python’s built-in functions, types, and exceptions. These names are always available without the need for import statements.
7. Explain the difference global (module) scope and local (function) scope.
Function Scope only includes names that are visible for that particular function. Whereas, the module scope includes names that are visible to the whole module / script.
8. Where is the global scope nested inside?
The global scope is nested inside the built-in scope.
9. Describe the order of finding variables through the nested scope.
It will look for the variable in an enclosing scope’s namespace first. If it is not found there, it will search in a different scope in the order of [Local → Global → Built-In Scope].
10. What happens to the local scope when the function finishes running?
Once the function finished running, the local scope and its namespaces will be destroyed.
11. How to modify a global variable inside a function?
global <var>: Set the global keyword
12. Explain the term inner functions.
Inner functions (also known as nested functions) are functions that are defined within a functions.
13. Explain the keyword nonlocal variable. Illustrate the concept of a nonlocal variable.

The nonlocal keyword is used to indicate that a variable is not local to the current function’s scope but is also not a global variable.

def outer_func():
    outer_variable = 100

    def inner_func():
        nonlocal outer_variable
        outer_variable = 200
        print("Inner:", outer_variable)

    inner_func()
    print("Outer:", outer_variable)

outer_func()

The nonlocal variable is found in the enclosing scope outer_func(). When inner_func() is called, python will search to outer_variable to print but it will not find it and then looks for the outer_variable in the enclosing scope (outer_func).

14. How to specify a nonlocal variable within a function?
nonlocal <var>
Last updated on 23 Aug 2024