dir() with string as argument

Terry Hancock hancock at anansispaceworks.com
Fri Jun 17 00:39:02 EDT 2005


On Thursday 16 June 2005 02:19 pm, harold fellermann wrote:
> On 16.06.2005, at 20:59, Shankar Iyer (siyer at Princeton.EDU) wrote:
> > Suppose I have a string, sModuleName, that contains the name of a 
> > module.  I now want to see what functions are in that module, but if I 
> > call dir(sModuleName), I instead get the list of operations that can 
> > be done on a string.  Is there any way to convert the string into a 
> > format that I could feed to dir to cause the desired effect?  I think 
> > I could modify the string a bit and then use the exec command, but I 
> > was advised against that on this board last week.
> 
> you have to import the module:
> 
> name = "sys"
> mod = __import__(name)
> dir(mod)

Note that if the module is already imported, this costs you almost
nothing --- __import__() will just return the already-loaded module.
That is to say:

import sys
dir(__import__('sys'))

is not going to take (noticeably) longer than:

mod = __import__('sys')
dir(mod)


--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list