Create classes at runtnime

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Feb 4 19:49:53 EST 2011


On Fri, 04 Feb 2011 11:17:39 -0800, Marc Aymerich wrote:

> Hi!
> I need to create a pretty complex class at runtime. something like this
> one:
> 
> (note: "...." means that the number of attributes can be variable)
>
> class VirtualUserLimitForm(ModelForm):
>     swap_limit = forms.CharField(max_length=100,
> initial=monitor1.default_limit)
>     memory_limit = forms.CharField(max_length=100,
> initial=monitor2.default_limit)
>     ...

[...]
> I can generate all the needed code as string and then use exec(), but it
> seems ugly to me. I'm wondering if there is another way more elegant to
> do that?  metaclasses maybe? What is your recommendation?

Just add in the class attributes you want after creating the class.

class VirtualUserLimitForm(ModelForm):
    pass


f = forms.CharField  # alias for brevity
for name, value in [
    ('swap_limit', f(max_length=100, initial=monitor1.default_limit)),
    ('memory_limit', f(max_length=100, initial=monitor2.default_limit)),
    ('spam', 'spam spam spam spam'),
    ('eggs', 'fried sunny side up'),
    ]:
    setattr(VirtualUserLimitForm, name, value)


There's probably a name for this sort of technique, and an entire chapter 
in "Design Patterns For People With Too Much Time On Their Hands" (15th 
edition), but I don't remember it :)



-- 
Steven



More information about the Python-list mailing list