> > 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? > > Just go through the objects in the module, test if they are classes, > subclasses of `A` and not `A` itself: > > from inspect import isclass > import test > > instances = dict() > for name in dir(test): > obj = getattr(test, name) > if isclass(obj) and issubclass(obj, test.A) and obj is not test.A: > instances[name] = obj()
Thanks, this looks pretty good. However there is some wierdness with isclass: whenever a class has a __getattr__ method an instance of it will be detected by isclass as a class (although it is not). >>> from inspect import isclass >>> >>> class x: ... def __getattr__( self, attr ): ... pass ... >>> y = x( ) >>> isclass( y ) True >>> If there is no __getattr__ method isclass works as expected. Am I misunderstanding something here or isclass should return False for any instance of any class including those with a __getattr__ method? -- http://mail.python.org/mailman/listinfo/python-list