Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What means of namespace object in Python

How to use types.new_class method in python3.3 later?
The following is sigunature.

types.new_class(name, bases=(), kwds=None, exec_body=None)  

How to use exec_body?
exec_body must be callable object, and it take a argument ns. (maybe it means namespace)
what type object should pass to ns?
According to documentation of new_class,

The exec_body argument is a callback that is used to populate the freshly created class namespace. It should accept the class namespace as its sole argument and update the namespace directly with the class contents. If no callback is provided, it has the same effect as passing in lambda ns: ns.

I have no idea meaning of above description about ns and exec_body.
How can I use this function?

like image 854
KiYugadgeter Avatar asked Mar 16 '17 12:03

KiYugadgeter


People also ask

Why is Python namespace used?

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".

How do you create a namespace object in Python?

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.

What is a namespace example?

Prominent examples for namespaces include file systems, which assign names to files. Some programming languages organize their variables and subroutines in namespaces. Computer networks and distributed systems assign names to resources, such as computers, printers, websites, and remote files.

What are the three types of namespaces in Python?

There are three types of Python namespaces- global, local, and built-in. It's the same with a variable scope in python. Also, the 'global' keyword lets us refer to a name in a global scope.


1 Answers

The namespace is a dictionary. You fill it with the attributes (including methods) that you want your new class object to have. Here's a simple demo.

import types

def body(ns):
    def __init__(self, a):
        self.a = a

    d = {
        '__doc__': 'A test class',
        'some_cls_attr': 42,
        '__repr__': lambda self: 'Test(a={})'.format(self.a),
        '__init__': __init__,
    }
    ns.update(d)

Test = types.new_class('Test', bases=(), kwds=None, exec_body=body)

print(Test.some_cls_attr)
print(Test('hello'))
#help(Test)

output

42
Test(a=hello)

Of course, for this simple example it's much more sensible to use the normal class creation syntax.

like image 193
PM 2Ring Avatar answered Oct 18 '22 21:10

PM 2Ring