Skip to content Skip to sidebar Skip to footer

What Is The Advantage In Using `exec` Over `type()` When Creating Classes At Runtime?

I want to dynamically create classes at runtime in python. For example, I want to replicate the code below: >>> class RefObj(object): ... def __init__(self, ParentClas

Solution 1:

I would recommend type over exec here.

In fact, the class statement is just syntactic sugar for a call to type: The class body is executed within its own namespace, which is then passed on to the metaclass, which defaults to type if no custom metaclass is specified.

This approach is less errorprone since there is no need to parse code at runtime, and might even be a bit faster.


Solution 2:

Why not just create a class in a function?

def foo_factory(index):
    name = 'Foo%d' % index

    class Foo(object):
        ref_obj = RefObj(name)

    Foo.__name__ = name
    return Foo

Solution 3:

There is no disadvantage to using type() over exec. I think Raymond's defense is a bit defensive. You have to choose the technique that you find most readable and understandable. Both ways create confusing code.

You should try really hard to avoid code that creates classes in the first place, that would be best.


Post a Comment for "What Is The Advantage In Using `exec` Over `type()` When Creating Classes At Runtime?"