Create classes at runtnime
__peter__ at web.de
Fri Feb 4 22:32:37 CET 2011
Marc Aymerich wrote:
> I need to create a pretty complex class at runtime. something like
> this one:
I have a hunch that you've never heard the famous Kernighan quote:
"Everyone knows that debugging is twice as hard as writing a program in the
first place. So if you're as clever as you can be when you write it, how
will you ever debug it?"
Or that if you've heard it you don't heed it.
> (note: "...." means that the number of attributes can be variable)
> class VirtualUserLimitForm(ModelForm):
> swap_limit = forms.CharField(max_length=100,
> memory_limit = forms.CharField(max_length=100,
> class Meta:
> model = model
> def __init__(self, *args, **kwargs):
> super(VirtualUserLimitForm, self).__init__(*args, **kwargs)
> if 'instance' in kwargs:
> self.fields['swap_limit'].initial =
> self.fields['memory_limit'].initial =
> 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?
The metaclass does indeed take a dictionary argument where you can provide
class attributes, e. g.:
>>> C = type("C", (), dict(a=1, b=lambda self: 42))
>>> C().a, C().b()
> What is your recommendation?
Find something that is simple and robust. Something else.
More information about the Python-list