Session Ready
Exercise

The __init__.py file

As you saw in the previous exercise you have to individually import models and utils to access functions and classes defined in each module. These modules do not get automatically imported when you run import mortgage_forecasts, since mortgage_forecasts is a directory.

To define what gets imported from a directory you need a file called __init__.py. This file is executed when import mortgage_forecasts is run.

For the mortgage_forecasts package we wish to provide a more convenient way to import MortgageRateModel from models.py and read_data from utils.py. Our goal is to tell users of the package that they can access these tools as

from mortgage_forecasts import read_data, MortgageRateModel

The mortgage_forecasts directory has been prepared for you.

Instructions 1/2
undefined XP
  • 1

    Create a new __init__.py file in /home/repl/mortgage_forecasts/mortgage_forecasts.

    Add this docstring at the top of the file. This allows the user to run help(mortgage_forcecasts) after importing the package.

    '''Predictive modeling of 30-year mortgage rates in the US.'''
    

    You can use nano, vi, vim, or emacs to edit the file.

    • 2

      Edit the __init__.py to add the following lines.

      from .models import MortgageRateModel
      from .utils import read_data
      

      Notice the use of . to mean the local directory of the __init__.py file. This helps avoid name collisions with other packages that have been installed.