Module inspection by name

Dave Angel davea at ieee.org
Tue Sep 22 16:00:27 EDT 2009


Jean-Michel Pichavant wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Nadav 
> Chernin wrote:
>>
>> Hi all, a have easy question for python developers.
>>
>> Assume I have list of all objects:
>>
>> obj=dir()
>>
>> Now I want to know which object from “obj” list is module.
>>
>> I searched some method in module inspection, but there is not any 
>> method that get ‘string’ as parameters
>>
>> Any reply will be greatfull
>>
>> Nadav
>>
>
> import sys
> import os
> name = 'os'
> sys.modules[name]
>
> will return the module itself with the string name. It should allow 
> you to use the method you found using the module itself.
>
> JM
>
> </div>
>
The right way to tell if an object is a module is to do isinstance(). 
But your first problem is that the return value of dir() is a list of 
strings, while you want a list of objects. I'd suggest you use globals() 
instead, which produces a dictionary of name/object pairs. Then iterate 
through the values, checking each type with isinstance().

Show us a sample of your code that doesn't work, and we'll try to show 
you how to fix it.

DaveA



More information about the Python-list mailing list