Creating new classes on the fly

Carlos Ribeiro carribeiro at gmail.com
Tue Oct 5 17:59:03 EDT 2004


On Tue, 5 Oct 2004 13:04:39 -0800, Troy Melhase <troy.melhase at gmail.com> wrote:
> I've had the same need recently, and I've found that coding the class
> as part of a closure is readable (untested code):
> 
> def my_custom_class():
>     some_param = lookup_param() # now part of the lexical scope, can be mutable
> 
>     class MyCustomClass:
>         default_param = some_param
> 
>     return MyCustomClass
> 
> CustomizedClass1 = my_custom_class()
> CustomizedClass2 = my_custom_class()
> 
> instances_of_one = [CustomizedClass1(), CustomizedClass1(), ]
> instances_of_two = [CustomizedClass2(), CustomizedClass2(), ]
> 
> Good luck,
> troy
 
I've done exactly that for one of my classes, for the first test.
However, I really felt that some better way should exist out of
creating an enclosing function for every one of the classes.

I've right now finished a small "class decorator" -- a function that
takes a class and a bunch of named parameters, and that returns a new
function that acts as a class constructor of sorts. It's something
like this:

next_id = itertools.count().next

def InheritedClassFactory(klass):
    def ClassDecorator(*args, **kw):
        newname = klass.__name__ + '_' + str(next_id())
        newklass = type(newname, (klass, ), kw)
        return newklass
    return ClassDecorator

MyClass = InheritedClassFactory(MyClass)

It's interesting that this is one situation where a metaclass isn't of
much help, while a class decorator does the trick. Of course, I'm
assuming that I really need to do it, but other solutions (not
involving the creation of new classes) may be better (but I'm not
aware of any such options).

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list