Create classes at runtnime

Peter Otten __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,
> initial=monitor1.default_limit)
>     memory_limit = forms.CharField(max_length=100,
> initial=monitor2.default_limit)
>     ...
> 
>     class Meta:
>         model = model
> 
>     def __init__(self, *args, **kwargs):
>         super(VirtualUserLimitForm, self).__init__(*args, **kwargs)
>         if 'instance' in kwargs:
>             self.fields['swap_limit'].initial =
> kwargs['instance'].monitoring.filter(monitor=monitor1)[0].current
>             self.fields['memory_limit'].initial =
> kwargs['instance'].monitoring.filter(monitor=monitor2)[0].current
>             ...
> 
> 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()
(1, 42)

> What is your recommendation?

Find something that is simple and robust. Something else.

Peter



More information about the Python-list mailing list