how to dynamically instantiate an object inheriting from several classes?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Nov 21 21:02:12 EST 2008


On Fri, 21 Nov 2008 15:11:20 -0700, Joe Strout wrote:

> I have a function that takes a reference to a class, 

Hmmm... how do you do that from Python code? The simplest way I can think 
of is to extract the name of the class, and then pass the name as a 
reference to the class, and hope it hasn't been renamed in the meantime:

def foo(cls_name, item_args):
    # Won't necessarily work for nested scopes.
    cls = globals()[cls_name]
    item = cls(**itemArgs)
    return item

instance = foo(Myclass.__name__, {'a':1})
        
Seems awfully complicated. If I were you, I'd forget the extra layer of 
indirection and just pass the class itself, rather than trying to 
generate some sort of reference to it. Let the Python virtual machine 
worry about what is the most efficient mechanism to use behind the scenes.


[...]
> But now I want to generalize this to handle a set of mix-in classes.
> Normally you use mixins by creating a class that derives from two or
> more other classes, and then instantiate that custom class.  But in my
> situation, I don't know ahead of time which mixins might be used and in
> what combination.  So I'd like to take a list of class references, and
> instantiate an object that derives from all of them, dynamically.
> 
> Is this possible?  If so, how?

It sounds like you need to generate a new class on the fly. Here's one 
way:

# untested
def foo(cls, item_args, mixins=None):
    superclasses = [cls] + (mixins or [])
    class MixedClass(*superclasses):
        pass
    item = MixedClass(**itemArgs)
    return item

instance = foo(MyClass, {'a':1}, [Aclass, Bclass, Cclass])


-- 
Steven



More information about the Python-list mailing list