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.

X = 1import mod2print X,print mod2.X,print mod2.mod3.X# My global X# mod2's X# Nested mod3's XReally, when mod1 imports mod2 here, it sets up a two-level namespace nesting. Byusing the path of names mod2.mod3.X, it can descend into mod3, which is nested in theimported mod2. The net effect is that mod1 can see the Xs in all three files, and hencehas access to all three global scopes:% python mod1.py2 31 2 3The reverse, however, is not true: mod3 cannot see names in mod2, and mod2 cannot seenames in mod1. This example may be easier to grasp if you don’t think in terms ofnamespaces and scopes, but instead focus on the objects involved. Within mod1, mod2is just a name that refers to an object with attributes, some of which may refer toother objects with attributes (import is an assignment). For paths like mod2.mod3.X,<strong>Python</strong> simply evaluates from left to right, fetching attributes from objects along theway.Note that mod1 can say import mod2, and then mod2.mod3.X, but it cannot say importmod2.mod3—this syntax invokes something called package (directory) imports,described in the next chapter. Package imports also create module namespace nesting,but their import statements are taken to reflect directory trees, not simple importchains.Reloading ModulesAs we’ve seen, a module’s code is run only once per process by default. To force amodule’s code to be reloaded and rerun, you need to ask <strong>Python</strong> to do so explicitlyby calling the reload built-in function. In this section, we’ll explore how to usereloads to make your systems more dynamic. In a nutshell:• Imports (via both import and from statements) load and run a module’s codeonly the first time the module is imported in a process.• Later imports use the already loaded module object without reloading or rerunningthe file’s code.• The reload function forces an already loaded module’s code to be reloadedand rerun. Assignments in the file’s new code change the existing moduleobject in-place.Why all the fuss about reloading modules? The reload function allows parts of a programto be changed without stopping the whole program. With reload, therefore,the effects of changes in components can be observed immediately. ReloadingReloading Modules | 409

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

Saved successfully!

Ooh no, something went wrong!