Exercise 4.1

Objectives:

  • How to create and use a library module.

  • Using the import statement

Files Created: None.

Files Modified: report.py

Caution

For this exercise involving modules, it is critically important to make sure you are running Python in proper environment.

If you are using IDLE, make sure that it is running in the SAME DIRECTORY as the directory where you are editing your solutions (e.g., "C:\practical-python"). If you started IDLE by clicking on the RunIDLE.pyw file, then it should already be set up.

If you’re not exactly sure where IDLE is running, restart the Python shell, import the os module and type os.getcwd() to get the current working directory. If it’s different than where you are saving files, you’ll need to quit IDLE and restart it from your working directory.

If you are unable to change the configuration of IDLE, you will have to manually adjust the system search path to load modules from the Python shell. For example:

>>> import sys
>>> sys.path.insert(0,'C:/practical-python')
>>>

(a) Module imports

In section 3, we created a general purpose function parse_csv() for parsing the contents of datafiles. Now, we’re going to see how to use that function in other programs.

Before beginning, restart the Python shell. To do this, first click in the window that has the interactive Python shell to make it active. Then, go up to the menu bar and look for the "Shell" option. Select that and click on the "Restart Shell" option. If this works, you should get a message like this:

>>> ================================ RESTART ================================
>>>

Once you’ve done that, try importing some of the programs you previously wrote. You should see their output exactly as before. Just emphasize, importing a module runs its code.

>>> import bounce
... watch output ...
>>> import mortgage
... watch output ...
>>> import report
... watch output ...
>>>

If none of this works, you’re probably running IDLE or Python in the wrong directory. See the big warning box above (also make sure the files actually exist—in case you skipped those exercises).

Now, try importing your fileparse module and getting some help on it.

>>> import fileparse
>>> help(fileparse)
... look at the output ...
>>> dir(fileparse)
... look at the output ...
>>>

Try using the module to read some data:

>>> portfolio = fileparse.parse_csv('Data/portfolio.csv',select=['name','shares','price'], types=[str,int,float])
>>> portfolio
... look at the output ...
>>> pricelist = fileparse.parse_csv('Data/prices.csv',types=[str,float], has_headers=False)
>>> pricelist
... look at the output ...
>>> prices = dict(pricelist)
>>> prices
... look at the output ...
>>> prices['IBM']
106.11
>>>

Try importing a function so that you don’t need to include the module name:

>>> from fileparse import parse_csv
>>> portfolio = parse_csv('Data/portfolio.csv', select=['name','shares','price'], types=[str,int,float])
>>> portfolio
... look at the output ...
>>>

(b) Using your library module

In section 2, you wrote a program report.py that produced a stock report like this:

      Name     Shares      Price     Change
---------- ---------- ---------- ----------
        AA        100      39.91       7.71
       IBM         50     106.11      15.01
       CAT        150      78.58      -4.86
      MSFT        200      30.47     -20.76
        GE         95      37.38      -2.99
      MSFT         50      30.47     -34.63
       IBM        100     106.11      35.67

Take that program and modify it so that all of the input file processing is done using functions in your fileparse module. To do that, import fileparse as a module and change the read_portfolio() and read_prices() functions to use the parse_csv() function. Use the interactive example at the start of this exercise as a guide.

(c) Using __main__

In your report.py program, the very last statement runs the program on some sample input files. For example:

portfolio_report('Data/portfolio.csv','Data/prices.csv')

Change this statement so that it only executes if the report.py program is run as the main script. Now, try to load your report.py program in two different ways. First, just run it as the main program by selecting Run Module in IDLE. If you are using the Unix shell, type this:

bash % python report.py

Next, restart Python and try loading it as a library module:

>>> ================================ RESTART ================================
>>> import report
>>>

If you have done this correctly, you will only get output when the program runs as main. When imported as a library module, you have to call the portfolio_report() function manually. For example:

>>> ================================ RESTART ================================
>>> import report
>>> report.portfolio_report('Data/portfolio.csv','Data/prices.csv')
... output here ...
>>>
Links