12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

To get around this, you need to use special tools to load a module dynamically froma string that is generated at runtime. The most general approach is to construct animport statement as a string of <strong>Python</strong> code, and pass it to the exec statement to run:>>> modname = "string">>> exec "import " + modname # Run a string of code>>> string # Imported in this namespaceThe exec statement (and its cousin for expressions, the eval function) compiles astring of code, and passes it to the <strong>Python</strong> interpreter to be executed. In <strong>Python</strong>, thebyte code compiler is available at runtime, so you can write programs that constructand 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.The only real drawback to exec is that it must compile the import statement each time itruns; if it runs many times, your code may run quicker if it uses the built-in _ _import_ _function to load from a name string instead. The effect is similar, but _ _import_ _returns the module object, so assign it to a name here to keep it:>>> modname = "string">>> string = _ _import_ _(modname)>>> stringfrom Copies Names but Doesn’t LinkAlthough it’s commonly used, the from statement is the source of a variety of potentialgotchas in <strong>Python</strong>. The from statement is really an assignment to names in theimporter’s scope—a name-copy operation, not a name aliasing. The implications ofthis are the same as for all assignments in <strong>Python</strong>, but subtle, especially given thatthe code that shares the objects lives in different files. For instance, suppose wedefine the following module (nested1.py):X = 99def printer( ): print XIf we import its two names using from in another module (nested2.py), we get copiesof those names, not links to them. Changing a name in the importer resets only thebinding of the local version of that name, not the name in nested1.py:from nested1 import X, printer # Copy names outX = 88# Changes my "X" only!printer( ) # nested1's X is still 99% python nested2.py99Module Gotchas | 439

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!