Python Glossary Русский

Python 3.3+typesfunction

types.new_class()

dynamic class creation

Creates a class on the fly exactly like the class statement: honouring the metaclass, __init_subclass__ and __mro_entries__. exec_body fills the body.

Syntax

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

type(name, bases, ns) is shorter, but it is just a call of the type metaclass: it does not understand bases like Generic[T] (they need __mro_entries__) and does not pass class keyword arguments (metaclass=..., your own __init_subclass__ parameters). new_class follows the same path as class. Trap: the new class reports types as its module unless you set ns['__module__'] in exec_body.

Examples

import types
class Base:
    def __init_subclass__(cls, tag='', **kw):
        super().__init_subclass__(**kw)
        cls.tag = tag
Child = types.new_class('Child', (Base,), {'tag': 'auto'},
                        lambda ns: ns.update(size=3))
print(Child.__name__, Child.tag, Child.size)  # → Child auto 3

See also

Open in the full glossarydocs.python.orgReport an inaccuracy