5

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?

1
  • Maybe start by using lambda. Or just leave it as None Commented Mar 16, 2017 at 12:27

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.