Modules and Multifile Applications

Importing

Objects sidebar

import length a = length.Length("4.5 yd")

Only modules that are in the current directory, or in Python's sys.path list, can be imported. If we need access to modules that are elsewhere in the filesystem, we can add additional paths to sys.path. In addition to a file, a module can be an entire directory of files. In these cases, the directory must contain a file called

_init_.py. This file can be (and often is) empty; it is simply used as a marker to tell Python that the directory contains .py files and that the directory name is the top-level module name. For example, we might create a directory called mylibrary and put length.py, ordereddict.py, and an empty_init_.py in it. As long as we add the directory that contains the mylibrary directory to Python's path, we could do this:

import mylibrary.length a = mylibrary.length.Length("14.3 km")

In practice, we might prefer to alias mylibrary.length to something shorter. For example:

import mylibrary.length as length a = length.Length("948mm")

Python's module handling is a lot more sophisticated than we have shown, but what we have covered is sufficient for the GUI programming which is our main concern.* Python and PyQt applications can be written in a single file or can be spread over multiple files. We will show both approaches in the coming chapters.

Object-oriented programming allows us to package up functionality (e.g., methods and data attributes), into classes. Python modules allow us to package up functionality at a higher level—for example, entire sets of classes, functions, and instance variables. A module is simply a file with a .py extension. Modules may have code that is executed when they are imported, but more commonly they simply provide functions and classes which are instantiated when they are imported. We have already seen examples of this: The Length class is in a file called length.py, and is therefore accessible as the length module. When importing a module, we specify the name of the module file without the extension. For example:

★The module import semantics are due to change in Python 2.7, with imports becoming absolute rather than relative. See http://www.python.org/dev/peps/pep-0328for details.

Was this article helpful?

0 0
Tuberminator

Tuberminator

The main focus of this report is to show how to get involved in video marketing on the run, how to rank quickly on YouTube and Google using FREE semi-automatic tools and services. QUICKLY AND FREE. I will show methods and techniques I use to rank my videos, as well as free resources and tools to make video clips, to get backlinks and free traffic.

Get My Free Ebook


Post a comment