15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Furthermore, we can go down one more subpackage for referencing:<br />

from Phone.Mobile import Analog<br />

Analog.dial('555-1212')<br />

In fact, you can go all the way down in the subpackage tree structure:<br />

from Phone.Mobile.Analog import dial<br />

dial('555-1212')<br />

In our above directory structure hierarchy, we observe a number of __init__.py files. These are<br />

initializer modules that are required when using from-import to import subpackages but they can be<br />

empty if not used. Quite often, developers forget to add _inti_.py files to their package directories, so<br />

starting in <strong>Python</strong> 2.5, this triggers an ImportWarning message.<br />

However, it is silently ignored unless the -Wd option is given when launching the interpreter.<br />

12.7.2. Using from-import with Packages<br />

Packages also support the from-import all statement:<br />

from package.module import *<br />

However, such a statement is dependent on the operating system's filesystem for <strong>Python</strong> to determine<br />

which files to import. Thus the __all__ variable in __init__.py is required. This variable contains all the<br />

module names that should be imported when the above statement is invoked if there is such a thing. It<br />

consists of a list of module names as strings.<br />

12.7.3. Absolute Import<br />

As the use of packages becomes more pervasive, there have been more cases of the import of<br />

subpackages that end up clashing with (and hiding or shadowing) "real" or standard library modules<br />

(actually their names). Package modules will hide any equivalently-named standard library module<br />

because it will look inside the package first to perform a relative import, thus hiding access to the<br />

standard library module.<br />

Because of this, all imports are now classified as absolute, meaning that names must be packages or<br />

modules accessible via the <strong>Python</strong> path (sys.path or PYTHONPATH).

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

Saved successfully!

Ooh no, something went wrong!