How do I create a Python namespace?

PythonServer Side ProgrammingProgramming

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. So if you want to create a namespace, you just need to call a function, instantiate an object, import a module or import a package. For example, we can create a class called Namespace and when you create an object of that class, you're basically creating a namespace.

Example

In this class, you can also pass variable names to attach to the namespace, for example,

class Namespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
args = Namespace(a=1, b='c')
print args.a, args.b

Output

This will give the output:

1 c
raja
Published on 21-Dec-2017 15:24:39
Advertisements