Exercise 10.6

Objectives:

  • Learn how to create a Python package.

(a) Making a package

A Python package is simply a collection of .py files in a directory. Let’s create a simple package. Follow these instructions carefully.

First, select "Restart Shell" option of IDLE to get a fresh Python session. Then make sure you’re running in the practical-python directory:

>>> import os
>>> os.getcwd()
'/Users/yourname/Desktop/practical-python'
>>>

Make a new directory for your package based on your last name. For example:

>>> os.mkdir('yourname')
>>>

Now, copy some of your Python files into the package:

>>> import shutil
>>> shutil.copy('fileparse.py','yourname')
>>> shutil.copy('stock.py','yourname')
>>> shutil.copy('report.py','yourname')
>>>

Now, try importing a package subcomponent:

>>> import yourname.fileparse
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    import yourname.fileparse
ImportError: No module named yourname.fileparse
>>>

It doesn’t work because you didn’t create an __init__.py file. Do that now by simply creating an empty file with that name:

>>> open('yourname/__init__.py','w').close()
>>>

Now, try importing a package subcomponent:

>>> import yourname.fileparse
>>> portfolio = yourname.fileparse.parse_csv('Data/portfolio.csv', types=[str, int, float])
>>>

Discussion: Most third-party add ons to Python will be installed as packages. For the most part, you don’t have to worry about it as a user (you will simply use import statements to load package components as needed). If you are building packages yourself, there are some tricky details you’ll need to worry about which have not been discussed here. Reading the online documentation or getting a good reference book would be advisable.

Links