how to dynamically instantiate an object inheriting from several classes?

Rafe rafesacks at gmail.com
Sun Nov 23 23:02:39 EST 2008


On Nov 22, 9:02 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> 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

I find type() is the better way to go because it allows you to name
the resulting class as well. It may make debugging a little easier.
Using a hard-coded class, such as "MixedClass" in the above example,
with dynamic bases produces lots of "MixedClass" instances with
different interfaces/abilities.

- Rafe



More information about the Python-list mailing list