reflection as in Java: how to create an instance from a classname

guss guillaume.aubert at gmail.com
Tue Jan 6 03:24:49 EST 2009


hi Thanks for the tip but I had to play with the __import__ func a
bit.
Indeed to load not only the top module with __import__ one needs to
try to load an object from the module:

Here is my forname:

def forname(modname, classname):
    module = __import__(modname,globals(),locals(),['NoName'],-1)
    classobj = getattr(module, classname)
    return classobj

Like that I can load MyError from the module org.myapp.exceptions

>>> c = forname('org.myapp.exceptions','MyError')
>>> instance = c('My Message')

If I do not put 'NoName' that is a fake object only module will be org
and not org.myapp.exceptions. This is strange ?

I think Python has all the elements for doing java like reflection and
introspection and even more but the API is not as mature and it is
quite difficult to find the information.
There is the need for a high level API.

Maybe it already exists, if anyone knows please tell me.
Thanks.

              Guillaume

On Jan 5, 5:34 pm, Bruno Desthuilliers <bruno.
42.desthuilli... at websiteburo.invalid> wrote:
> guss a écrit :
>
>
>
> > I cannot find a satisfying answer to this question on the web so let's
> > try here.
>
> > My problem is the following, I would like to instantiate some object
> > from a configuration file that would contain class names like for
> > example classname=org.common.resource.MyResource.
> > Here my resource is the class to instanciate and it is in the module
> > resource that is in a package hierachy.
>
> > In fact I would like to do something very similar to the Java:
>
> > klass = Class.forname("org.common.resource.MyResource")
>
> > instance = klass.newInstance()
>
> > The second line is easy once I have a classobj but I have some
> > problems to find the right recipe for getting it.
>
> > I know how to create a class from scratch with new.classobj but how do
> > you get a class object and then create an object ?
>
> > I would like a recipe working for all cases (whatever the module is
> > not the local one ...)
>
> use __import__ to get the module object, then getattr(module, classname)
> to get the class object (sorry, no much time right now to give you a
> full recipe, but that should be enough to get you started).
>
> HTH




More information about the Python-list mailing list