Module Gotchas

Finally, here is the usual collection of boundary cases, which make life interesting for beginners. Some are so obscure it was hard to come up with examples, but most illustrate something important about Python.

Importing Modules by Name String

As we’ve seen, the module name in an import or from statement is a hardcoded variable name; you can’t use these statements directly to load a module given its name as a Python string. For instance:

>>> import "string"
  File "<stdin>", line 1
    import "string"
                  ^
SyntaxError: invalid syntax

Solution

You need to use special tools to load modules dynamically, from a string that exists at runtime. The most general approach is to construct an import statement as a string of Python code and pass it to the exec statement to run:

>>> modname = "string"
>>> exec "import " + modname       # run a string of code
>>> string                         # imported in this namespace
<module 'string'>

The exec statement (and its cousin, the eval function) compiles a string of code, and passes it to the Python interpreter to be executed. In Python, the bytecode compiler is available at runtime, so you can write programs that construct and run other programs like this. By default, exec runs the code in the current scope, but you can get more specific by passing in optional namespace dictionaries. We’ll say more about these tools later in this book.

The only real drawback to exec is that it must compile the import statement each time it runs; if it runs many times, you might be better ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.