python


Python Namespace


Namespace

A namespace is a mapping from names to objects.
Most namespaces are currently implemented as Python dictionaries, but that’s normally not noticeable in any way (except for performance), and it may change in the future.
Examples of namespaces are: the set of built-in names (containing functions such as abs(), and built-in exception names); the global names in a module; and the local names in a function invocation. In a sense the set of attributes of an object also form a namespace.
I use the word attribute for any name following a dot — for example, in the expression z.real, real is an attribute of the object z. Strictly speaking, references to names in modules are attribute references: in the expression modname.funcname, modname is a module object and funcname is an attribute of it.

  1. Built-in Namespace
  2. When Python interpreter runs solely without and user-defined modules, methods, classes, etc. Some functions like print(), id() are always present, these are built in namespaces.

  3. Global Namespace
  4. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits. The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__, so they have their own global namespace. (The built-in names actually also live in a module; this is called builtins.)

  5. Local Namespace
  6. The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function. (Actually, forgetting would be a better way to describe what actually happens.) Of course, recursive invocations each have their own local namespace.

Note:The built-in namespace encompasses global namespace and global namespace encompasses local namespace.
Example 1:

def first_func():
    M = 25
    def second_func():
        N = 36

O = 16


In the example 1, the variable O is in the global namespace. Variable M is in the local namespace of first_func() and N is in the nested local namespace of second_func().
When we are in second_func(), N is local to us, M is nonlocal and O is global.
Example 2:


def outer_function():
    global M
     M= 25

    def inner_function():
        global M
        M = 36
        print('a =', M)

    inner_function()
    print('a =', M)


M = 16
outer_function()
print('a =', M)
        
        
        
        
        
Output:

a = 36
a = 36
a = 36

In example 2, we declared M as global, the reference and assignment will go to M and also in this program we declared 3 diffrent variables as Mwhich are defined in their seperate namespace from which they can be accessed further.