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

Alex Martelli aleaxit at yahoo.com
Mon Jan 29 09:25:19 EST 2001


"Andre Fortin" <andrefor at axionet.com> wrote in message
news:3A74E327.C02A86FC at axionet.com...
    [snip]
> > try:
> >     callable = test.myFunc
> > except (NameError,AttributeError):
> >     pass
> > else:
> >     callable('Some Text')
>
> Using "test.myFunc" returns a "AttributeError: myFunc", since
> "test" is a string.

The quotes are confusing, but I assume you mean that 'test'
is not ITSELF the name of the object, but rather _refers to_
a string which is the name of the object.  If so, then
        callable = eval(test+'.myFunc')
may be the simplest way to apply this "indirectness".

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

> try:
>     sys.modules[className].myFunc('Some text')
> except KeyError:
>     pass

This will propagate an AttributeError if a module
named 'test' exists but does NOT contain an entry
called 'myFunc' (as well as a TypeError if that
entry exists but is not callable with one argument,
as before).

> Very clean. It avoids both the globals() and vars() calls.
>
> > (a KeyError raised inside 'callable' in your case
> > is silently caught and hidden -- IS that what you want?)
>
> In my case, yes. In this snippet context, what counts is the existence
> of the "test" module.

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


Alex






More information about the Python-list mailing list