Create a new class on the fly

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed May 30 22:38:42 EDT 2007


On Wed, 30 May 2007 17:44:06 -0700, py_genetic wrote:

> 
> Is this possible or is there a better way.  I need to create a new
> class during runtime to be used inside a function. The class
> definition and body are dependant on unknows vars at time of exec,
> thus my reasoning here.

You might want a class factory, a function that returns a class, or a
metaclass, a class that returns classes.

Building the class definition as a string at runtime and then using exec
(not eval) to create the class is probably the most obvious way of doing
it, but it isn't very convenient, and if you are getting any part of the
string from a source not under your control (e.g. a web form) you're
opening yourself up to a world of security holes.

The cleaner, safer, more convenient ways of building classes at runtime is
to use the Python metaclass machinery, perhaps wrapped in a function for
convenience. See here for examples:

http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html



-- 
Steven.




More information about the Python-list mailing list