Loading a class the name of which is only known runtime

Mike C. Fletcher mcfletch at rogers.com
Tue Apr 8 21:23:46 CEST 2003


In case Mads wanted something a little more fleshed out ;) .  This is 
from basictypes, pretty simple little function that's part of the 
late-binding machinery.  Note that this requires the class to be defined 
in the top-level of it's module.

def importByName( fullName ):
    """Import a class by name"""
    name = fullName.split(".")
    moduleName = name[:-1]
    className = name[-1]
    module = __import__( ".".join(moduleName), {}, {}, moduleName)
    return getattr( module, className )

Enjoy,
Mike


Bjarke Dahl Ebert wrote:

>"Mads Orbesen Troest" <mads at troest.NEVERMORE.dk> wrote in message
>
>  
>
>>Actually, what I am looking for is more alone the lines of:
>>
>>moduleToImport = "SomeModule" # <- Retrieved as CGI argument
>>classToInstantiate = "SomeClass" # <- Retrieved as CGI argument
>>
>>import moduleToImport
>>someInstance = classToInstantiate()
>>    
>>
...

>There is a slight complication, though:
>If themodulename is of the form "foo.bar", then module foo is returned. Some
>themodulename.split('.'), and additional getattr calls should help.
>  
>
...

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/








More information about the Python-list mailing list