12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

import dir1.dir2.mod # Later imports do not>>>>>> reload(dir1)dir1 init>>>>>> reload(dir1.dir2)dir2 initOnce imported, the path in your import statement becomes a nested object path inyour script. Here, mod is an object nested in the object dir2, which in turn is nested inthe object dir1:>>> dir1>>> dir1.dir2>>> dir1.dir2.modIn fact, each directory name in the path becomes a variable assigned to a module objectwhose namespace is initialized by all the assignments in that directory’s _ _init_ _.pyfile. dir1.x refers to the variable x assigned in dir1\_ _init_ _.py, much as mod.z refers tothe variable z assigned in mod.py:>>> dir1.x1>>> dir1.dir2.y2>>> dir1.dir2.mod.z3from Versus import with Packagesimport statements can be somewhat inconvenient to use with packages because youmay have to retype the paths frequently in your program. In the prior section’s example,for instance, you must retype and rerun the full path from dir1 each time youwant to reach z. If you try to access dir2 or mod directly, you’ll get an error:>>> dir2.modNameError: name 'dir2' is not defined>>> mod.zNameError: name 'mod' is not definedIt’s often more convenient, therefore, to use the from statement with packages toavoid retyping the paths at each access. Perhaps more importantly, if you everrestructure your directory tree, the from statement requires just one path update inyour code, whereas the import may require many. The import as extension, discussedPackage Import Example | 419

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

Saved successfully!

Ooh no, something went wrong!