file ""line import "stringsyntaxerrorinvalid syntax it also won' work to simply assign the string to variable namex 'stringimport herepython will try to import file pynot the string module--the name in an import statement both becomes variable assigned to the loaded module and identifies the external file literally running code strings to get around thisyou need to use special tools to load module dynamically from string that is generated at runtime the most general approach is to construct an import statement as string of python code and pass it to the exec built-in function to run (exec is statement in python xbut it can be used exactly as shown here--the parentheses are simply ignored)modname 'stringexec('import modnamerun string of code string imported in this namespace we met the exec function (and its cousin for expressionsevalearlierin and it compiles string of code and passes it to the python interpreter to be executed in pythonthe byte code compiler is available at runtimeso you can write programs that construct and run other programs like this by defaultexec runs the code in the current scopebut you can get more specific by passing in optional namespace dictionaries if needed it also has security issues noted earlier in the bookwhich may be minor in code string you are building yourself direct callstwo options the only real drawback to exec here is that it must compile the import statement each time it runsand compiling can be slow precompiling to byte code with the compile built-in may help for code strings run many timesbut in most cases it' probably simpler and may run quicker to use the built-in __import__ function to load from name string insteadas noted in the effect is similarbut __import__ returns the module objectso assign it to name here to keep itmodname 'stringstring __import__(modnamestring advanced module topics