A concrete example

The rest of this chapter will use a running example to illustrate the inner workings of the package mechanism (see figure 18.2). Filenames and paths are shown in plain text, to avoid confusion as to whether we're talking about a file/directory or the module/package defined by that file/directory. The files we'll be using in our example package are shown in listings 18.1 through 18.6.

Listing 18.1 File mathproj/_init_.py print("Hello from mathproj init")

version = 1.03

Listing 18.2 File mathproj/comp/_init_.py

print("Hello from mathproj.comp init")

print("Hello from mathproj.comp init")

Figure 18.2 Example package

Listing 18.3 File mathproj/comp/cl.py x = 1.00

Listing 18.4 File mathproj/comp/numeric/_init_.py print("Hello from numeric init")

Listing 18.5 File mathproj/comp/numeric/nl.py from mathproj import version from mathproj.comp import c1 from mathproj.comp.numeric.n2 import h def g():

print("version is", version) print(h())

Listing 18.6 File mathproj/comp/numeric/n2.py def h():

return "Called function h in module n2"

For the purposes of the examples in this chapter, we'll assume that you've created these files in a mathproj directory that's on the Python search path. (It's sufficient to ensure that the current working directory for Python is the directory containing math-proj when executing these examples.)

NOTE In most of the examples in this book, it's not necessary to start up a new Python shell for each example. You can usually execute them in a Python shell you've used for previous examples and still get the results shown. This isn't true for the examples in this chapter, because the Python namespace must be clean (unmodified by previous import statements) for the examples to work properly. If you do run the examples that follow, please ensure that you run each separate example in its own shell. In IDLE, this requires exiting and restarting the program, not just closing and reopening its Shell window.

Was this article helpful?

0 0

Post a comment