Create classes at runtnime

Ian ian.g.kelly at
Sat Feb 5 02:19:23 CET 2011

On Feb 4, 5:49 pm, Steven D'Aprano <steve
+comp.lang.pyt... at> wrote:
> 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)

This would probably cause some problems with the Django metaclass.  It
inspects the class dictionary for fields at the time the class in
constructed, and so it would miss any fields added after construction

More information about the Python-list mailing list