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.

from module import X. . .reload(module)X# X may not reflect any module reloads!# Changes module, but not my names# Still references old objectTo make reloads more effective, use import and name qualification instead of from.Because qualifications always go back to the module, they will find the new bindingsof module names after reloading:import module. . .reload(module)module.X# Get module, not namesreload, from, and Interactive Testing# Changes module in-place# Get current X: reflects module reloadsChapter 3 warned that it’s usually better not to launch programs with imports andreloads because of the complexities involved. Things get even worse when from isbrought into the mix. <strong>Python</strong> beginners often encounter the gotcha described here.After opening a module file in a text edit window, say you launch an interactive sessionto load and test your module with from:from module import functionfunction(1, 2, 3)Finding a bug, you jump back to the edit window, make a change, and try to reloadthe module this way:reload(module)But this doesn’t work—the from statement assigned the name function, not module.To refer to the module in a reload, you have to first load it with an import statementat least once:import modulereload(module)function(1, 2, 3)However, this doesn’t quite work either—reload updates the module object, but asdiscussed in the preceding section, names like function that were copied out of themodule in the past still refer to the old objects (in this instance, the original versionof the function). To really get the new function, you must call it module.functionafter the reload, or rerun the from:import modulereload(module)from module import functionfunction(1, 2, 3)Now, the new version of the function will finally run.Module Gotchas | 441

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

Saved successfully!

Ooh no, something went wrong!