Dergum
Dergum

Reputation: 43

How to dynamically import modules with exec

Now I want to built a function get_doc( ) which can get the doc of the module Here's the code

def get_doc(module):
    exec "import module"
    print module.__doc__

And the information returned:

Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    get_doc(sys)
NameError: name 'sys' is not defined

Upvotes: 4

Views: 1951

Answers (2)

thefourtheye
thefourtheye

Reputation: 239493

When you say

get_doc(sys)

python will not be able to recognize sys. The actual way to do what you are trying to do would be to

  1. pass the module name as a string parameter

  2. use __import__ function to load the module, like this

    def get_doc(module):
        mod = __import__(module)
        print mod.__doc__
    
    get_doc("sys")
    

Note: I am not in favor of executing dynamic code in programs, but if you must use exec to solve this problem read this and have a basic understanding about the security implications and then look at aIKid's solution.

Upvotes: 2

aIKid
aIKid

Reputation: 28292

The problem is you're importing "module" instead of the specified module, and you didn't put the name module anywhere. A stupid fix to this would be to always using exec

def get_doc(module):
    exec "import {}".format(module)
    exec "print {}.__doc__".format(module)"

But instead of exec, i would advise you to use the __import__ function:

def get_doc(module):
    module = __import__(module)
    print module.__doc__

Which allows more flexibility, and you can modify, use module as you wanted.

Upvotes: 4

Related Questions