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

Alex Martelli aleaxit at yahoo.com
Sun Jan 28 13:40:12 EST 2001


"Andre Fortin" <andrefor at axionet.com> wrote in message
news:3A745F5E.5F035F1D at axionet.com...
> Hi!,
>
>
> I'm trying to do the following: if there is an object named 'test' in
> this namespace, call its well-known class method 'myFunc'.

There are no "class methods" in Python.  Further, your snippet is
actually doing something different: if there is an object named
'test' in your current global namespace, and it has a __dict__
attribute, which contains a key named 'myFunc', it attempts
to call the value corresponding to that key with a single argument,
the string 'Some text'; you ignore any KeyError raised during
these operations, but not others (e.g. if myFunc exists but is
not callable, or not with exactly one argument, the exception
is not caught).

> Is there a better/easier way, avoiding globals() and vars() ?

There are slightly different ways, but it's hard to say whether
they're better or easier.  globals() is probably the best way to
get at your current module's global variables -- alternatives
such as sys.modules[__name__].__dict__ appear anything
but 'better' or 'easier' to me.  But the usual 'easier to get
forgiveness than permission' rule applies -- just try to use
name test and catch the NameError that may result!

Looking up an attribute of an object seems best performed
with getattr() than via vars().  But again try/except is
simpler -- here, just catch the possible AttributeError.

So, a solution might be:

try:
    callable = test.myFunc
except (NameError,AttributeError):
    pass
else:
    callable('Some Text')

These are 6 lines, versus your 5, but they do look simpler,
clearer, and easier to me (and, one could compact them
into 3 if willing to brave the One True Python Style's
Defenders:-).  There ARE little differences with your
snippet (a KeyError raised inside 'callable' in your case
is silently caught and hidden -- IS that what you want?),
but they're not hard to remove if needed.


Alex






More information about the Python-list mailing list