How to call a class method from a string representing a class name

Andre Fortin andrefor at axionet.com
Tue Jan 30 01:11:53 EST 2001


Alex Martelli wrote:
[snip]


> > import sys
> > import test
> >
> > className = 'test'
> 
> Why call 'className' what is actually the name of a
> MODULE, *NOT* of a class?  Seems confusing.  Or, may
> the name be of _something else_ than a module...?

The confusion comes from the fact that the module 'test' contains a
class named 'test'. What matters here is really that the 'test' module
has been imported in the current namespace.

 
> If you KNOW it's a module (not "just any object
> whatsoever") then I guess indexing into sys.modules
> is OK. But, IS this part of the specs?  I saw you
> originally specify that you were naming *an object
> in the current global namespace*, and sys.modules
> does not check that -- if any OTHER module has ever
> imported one named 'test', then the entry WILL be
> in sys.modules, even if 'THIS module here' has never
> heard about it.  So, you're implementing pretty
> different specs -- "modules only" as opposed to
> any object, "ever imported anywhere" as opposed to
> "in the current global namespace"

This is a problem. Here is the semantic I'm trying to achieve:


If 'THIS module here' has heard of a module named 'test'
	call test.myFunc, which must exist according to the specs
	if test.myFunc returns false,
		 instantiate test.test and use it for further processing


Hmmm. It looks like the sys.modules is not what I'm looking for. You are
suggesting

> callable = eval(test+'.myFunc')
 
which is likely to be more costly compared to what I started with e.g.

try:
    myObj = globals()[className]
    apply(vars(myObj)['myFunc'], ('Some text',))
except KeyError:
    pass


Are we back to the beginning ?


-- 

Andre



More information about the Python-list mailing list