Best way to create a class dynamically on the fly?

Chad Netzer cnetzer at
Sun Sep 29 04:35:34 CEST 2002

On Saturday 28 September 2002 19:08, Robert Oschler wrote:
> I understand but what I'm after is building the class itself
> dynamically, akin to the way you can manufacture a prolog predicate
> on the fly.  For example,  if wanted to create a class whose name was
> provided in a string variable called ClassName, at runtime.  Or did I
> misunderstand your reply?

Well, you could create a class at runtime, given a class name, using 
several techniques; But what would be the code?  Do you mean selecting 
from various classes (pre-made) given a string?  Or would the class 
code be generated on the fly?

Perhaps you mean you want to choose, at runtime, which class to 
instantiate given a string, such as in a Factory pattern.

ie:  (extremely simple example)

class Foo:
    def __init__( self ):

def factory( name ):
    if name == 'dict':
        return {}       # An instance of a class
    elif name == 'list':
        return []       # Another instance
    elif name == 'foo':
        return Foo()    # A user defined class
        return None

This is creating an instance on the fly, given a name at runtime, 
rather than a class, but unless you are doing meta programming, I think 
perhaps it is what you mean (and I apologize if otherwise)

Here is a Python Cookbook entry on Factory patterns, BTW.:

BTW, rather than returning the instance, you could return the class 
object itself, to be instantiated later (ie. "return Foo", instead of 
"return Foo()")


Chad Netzer
cnetzer at

More information about the Python-list mailing list