Dynamic call of a method : error

Volucris volucris at hotmail.com
Wed Jul 4 19:28:41 EDT 2001


--

Volucris (a) hotmail.com
"Eu não falo uma única palavra do português."

"Dublanc, David" <ddublanc at free.fr> wrote in message
news:3pM07.8236$Yq2.6098008 at nnrp5.proxad.net...
> Hello, when I execute the module :
> ***************
> L = []
>
> for method in dir(L):
>     "dynamic call"
>     print L.method.__doc__
> ****************
>
> I have the following error :
>
> PythonWin 2.1 (#15, Apr 23 2001, 18:00:35) [MSC 32 bit (Intel)] on win32.
> Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com) - see
> 'Help/About PythonWin' for further copyright information.
> Traceback (most recent call last):
>   File "f:\python21\pythonwin\pywin\framework\scriptutils.py", line 301,
in
> RunScript
>     exec codeObject in __main__.__dict__
>   File "G:\script python\test concaténation.py", line 5, in ?
>     print L.method.__doc__
> AttributeError: method
>
>
> How can I call a method dynamically ?
>
> Thanks.
>
> Regards,
> --
> David
>

Remember that dir() returns a list of _strings_, so method is the name of
the
function (or whatever's in the module) not the actual function. Strings
don't
have a 'method' attribute. That is where the exception comes from. Try this:

#the name of the module you're digging in dynamically
mod_name = 'gc'

#import the module dynamically
exec 'import %s' % mod_name

#create a copy of the module dynamically
mod_copy = eval('%s' % mod_name)

for method in dir(mod_copy):
    try:
        #retrieve each member's docstring dynamically...
        print eval('%s.%s' % (mod_name, method)).__doc__
    except AttributeError:
        #unless it can't have one (ints, floats, etc.)
        print 'No \'__doc__\' for %s.' % method


Please excuse the excessize use of the word 'dynamically'. I really like
that word.

--

Volucris (a) hotmail.com
"Eu não falo uma única palavra do português."





More information about the Python-list mailing list