instantiate all subclasses of a class

Simon Forman rogue_pedro at yahoo.com
Sun Jul 16 12:18:57 EDT 2006


Daniel Nogradi wrote:
> > > What is the simplest way to instantiate all classes that are
> > > subclasses of a given class in a module?
> > >
> > > More precisely I have a module m with some content:
> > >
> > > # m.py
> > > class A:
> > >     pass
> > > class x( A ):
> > >     pass
> > > class y( A ):
> > >     pass
> > > # all kinds of other objects follow
> > > # end of m.py
> > >
> > > and then in another module I have currently:
> > >
> > > # n.py
> > > import m
> > > x = m.x( )
> > > y = m.y( )
> > > # end of n.py
> > >
> > > and would like to automate this in a way that results in having
> > > instances of classes from m in n whose names are the same as the
> > > classes themselves. But I only would like to do this with classes that
> > > are subclasses of A.
> > >
> > > Any ideas?
> >
> > It's pretty easy
> >
> >
> > import m
> > from inspect import getmembers, isclass, getmro
> >
> > t = '%s = m.%s()'
> >
> > for name, class_ in getmembers(m, isclass):
> >     if class_ is m.A:
> >         continue
> >     if m.A in getmro(class_):
> >         exec t % (name, name)
> >
>
> Actually, this variant also suffers from the broken isclass implementation.
>
> (Simon, sorry for the double post.)


Not a problem,  I haven't used inspect much so I've not been bitten by
this bug before.  It's good to know!

(I would have assumed that isclass() would have been implemented as
isinstance(obj, (types.ClassType, type))  anyway.   I'm surprised it's
not,  and that it's so broken..)

Thanks.




More information about the Python-list mailing list