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

Carl Banks pavlovevidence at
Tue Jan 6 10:29:00 CET 2009

On Jan 6, 2:24 am, guss <guillaume.aub... at> wrote:
> 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 ?

Yes, it's strange.  It's that way for historical and logistical
reasons.  Here's how I'd write the function; no need to specify
modname and classname separately.

def forname(name):
    parts = name.split(".")
    obj = __import__(".".join(parts[:-1]))
    for part in parts[1:]:
        obj = getattr(obj,part)
    return obj

> 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.

I'm going to suggest that the reason high-level reflection APIs are
used so often in Java is to compensate for Java's lack of run-time
flexibility.  If you don't know what class to use or method to call at
compile-time, the easiest thing to do is to store the name in a string
and use the Reflection API to get at it at run-time.

Python, OTOH, is very dynamic, so there is not much demand for spiffy
introspection APIs.  Functions and classes are ordinary objects, so if
you don't know what function to call or class to use at compile-time,
you can just pass the objects around.  No strings required.

So what I'm saying is: the Python developers didn't bother to make an
high-level, easy-to-use __import__ because there really isn't much
demand for it.

Carl Banks

More information about the Python-list mailing list