How to instatiate a class of which the name is only known at runtime?

Tomasz Lisowski jtlis at pf.NOSPAM.pl
Mon Sep 15 22:22:17 CEST 2003


Uzytkownik "Peter Otten" <__peter__ at web.de> napisal w wiadomosci
news:bjml1l$fd9$00$1 at news.t-online.com...
> Marco Herrn wrote:
>
> > 1. How to do the import? I didn't find a way to give a string to the
> >    import statement.
> >
> > 2. How to write such code to instantiate?
>
> Off topic: This thread like some others is spread over a few toplevel
> entries in my newsreader (KNode 0.7.2). Is this a bug?
>
> Anyway, putting it all together:
>
> import sys
>
> def getClass(classname, modulename):
>     try:
>         module = sys.modules[modulename]
>     except KeyError:
>         module = __import__(modulename)
>     return getattr(module, classname)

Hmm...

Why not write it directly:

def getClass(classname, modulename):
    try:
        module = __import__(modulename)
    except ImportError:
        return None
    else:
        return getattr(module, classname)

I have heard, that the __import__ function is smart enough to check the
sys.modules dictionary without actually re-importing the once imported
module. Is it true?

Regards,
Tomasz Lisowski







More information about the Python-list mailing list