Carlo Sogono wrote: > I need to be able to load and access Python classes based on a module and > class names defined by strings. So let's say someone passes > 'MyFavouriteClass' and 'somemodule'. I would like to be able to access > MyFavouriteClass() within the module somemodule. Is this at all possible? > And if not, what are my options to achieve something similar? Basically my > application must be passed a name of a module and class so that we can > access it.
Use __import__ and getattr, e.g.: the_class = getattr(__import__('somemodule'), 'MyFavouriteClass') It gets a little more complicated if packages (i.e. module names with dots in them) are involved. See the __import__ docs at http://docs.python.org/lib/built-in-funcs.html for more details. If you already have the Twisted libraries installed, then there's a convenience function you can use called “namedAny”: from twisted.python.reflect import namedAny the_class = namedAny('somemodule.MyFavouriteClass') -Andrew. _______________________________________________ coders mailing list coders@slug.org.au http://lists.slug.org.au/listinfo/coders