Dynamic call of a method : error

Thomas Wouters thomas at xs4all.net
Sat Jul 7 11:08:49 EDT 2001


On Wed, Jul 04, 2001 at 06:28:41PM -0500, Volucris wrote:

> #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)

Or, more efficient and more readable (IMHO):

mod_copy = __import__(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

'getattr()' is much more appropriate than eval() here, and in fact in most
places. The tree-argument version is also particularly useful in this case:

for method in dir(mod_copy):
    print getattr(mod_copy, method, "No docstring for %s"%method)

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

Not as much as you seem to like 'eval' and 'exec' :-)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list