Explain python namespace and scope of a variable.



In Python, a namespace is a mapping between names and objects. Namespaces are used to prevent naming conflicts and provide a way to organise code. The scope of a variable refers to the part of the code where the variable can be accessed. Understanding namespaces and variable scopes is important for writing clean and maintainable code.

Namespaces are 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. Additionally, there's a global namespace that's used if the name isn't in the local namespace.

Scope defines the visibility of an object. It defines where an object can be accessed.

  • The scope variable is local or global
  • The variable defined within the block has local scope. They are visible only to the block in which they are defined.
  • The variable defined in global area is visible from their definition until the end of program. It is visible everywhere in program.
  • 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.

Here are some examples to illustrate namespaces and variable scopes in Python:

Global Namespace:

Example

In this example, the variable `a` is defined in the global namespace. The function my_function() can access the global variable `a` since it is in the same namespace.

a = 10  # Global variable
def my_function():
    print(a)  # Access global variable
my_function()  

Output

The above code produces the following output

10
 

Local Namespace:

Example

In this example, the variable a is defined in the local namespace of my_function(). This means that the variable a is only accessible within the function.

def my_function():
    a = 10  # Local variable
    print(a)
my_function() 

Output

The above code produces the following output

10
 

Function Parameters:

Example

In this example, the variable a is a parameter to the function my_function(). The parameter a is in the local namespace of the function and can be accessed within the function.

def my_function(a):
    print(a)
my_function(10)

Output

The above code produces the following output

10
 

Nested Functions:

Example

In this example, the function inner_function() is defined within outer_function(). The variable a is in the local namespace of outer_function() and can be accessed within inner_function().

def outer_function():
    a = 10  # Local variable of outer_function
    def inner_function():
        print(a)  # Access variable of outer_function
    inner_function()
outer_function()  

Output

The above code produces the following output

10
 

Changing Global Variable from a Function:

Example

In this example, the function my_function() changes the value of the global variable a using the global keyword. This allows the function to modify the global variable.

a = 10  # Global variable
def my_function():
    global a
    a = 20  # Change global variable
my_function()
print(a)

Output

The above code produces the following output

20
 

Accessing Built-in Names:

Example

In this example, the built-in function abs() is called to get the absolute value of -10. The function max() is also defined in the global namespace and can be accessed.

a = abs(-10)  # Call built-in function abs()
def max(x, y):
    return x if x > y else y
print(max(10, 20))  # Call user-defined function max()

Output

The above code produces the following output

20
 

Local Namespace and Global Namespace:

Example

In this example, the function my_function() defines a local variable `a` that shadows the global variable `a`. To access the global variable from within the function, we can use the globals() function, which returns a dictionary containing the global variables.

a = 10  # Global variable
def my_function():
    a = 20  # Local variable
    print("Local variable a =", a)
    print("Global variable a =", globals()['a'])
my_function()
print("Global variable a =", a)

Output

The above code produces the following output

Local variable a = 20
Global variable a = 10
Global variable a = 10
 

Note that the global variable `a` is not affected by the local variable `a`.

In conclusion, namespaces and variable scopes are important concepts in Python. Understanding how they work can help you write cleaner and more maintainable code.


Advertisements