Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating classes - Python

Tags:

I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form class.

By "dynamically" I intend to create a class based on configuration provided by a user.


e.g.

I want a class named CommentForm which should subclass the Form class.

The class should have a list of chosen attributes.

....in this case

name = forms.CharField() comment = forms.CharField(widget=forms.Textarea()) 

Any useful tips? :)

like image 857
RadiantHex Avatar asked Oct 12 '10 13:10

RadiantHex


People also ask

What is a dynamic class?

Dynamic Class Loading allows the loading of java code that is not known about before a program starts. Many classes rely on other classes and resources such as icons which make loading a single class unfeasible. For this reason the ClassLoader ( java. lang.

Can we create a class at runtime?

Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance.

Is it good practice to use classes in Python?

Classes are great if you need to keep state, because they containerize data (variables) and behavior (methods) that act on that data and should logically be grouped together. This leads to code that is better organized (cleaner) and easier to reuse.

Can you create classes in Python?

A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class .


1 Answers

You can create classes on the fly by calling the type built-in, passing appropriate arguments along, like:

CommentForm = type("CommentForm", (Form,), {      'name': forms.CharField(),     ... }) 

It works with new-style classes. I am not sure, whether this would also work with old-style classes.

like image 179
Dirk Avatar answered Sep 20 '22 16:09

Dirk