Modules and Packages

From Training Material
Jump to navigation Jump to search


What is a module?

Any Python file (ending .py) can be imported from another Python script to use it as a library. A single Python file is also called a module.

Importing modules

To import from a module, its name (without .py) needs to be given in the import statement. Often, it is helpful to list the variables and functions required explicitly (helps with ebugging). Package names may be given as well.

import fruit

from fruit import fruit_prices

from my_package import fruit

What are the .pyc files for?

When importing, Python generates bytecode files (.pyc) that help to execute programs faster. They are managed automatically, and dont need to be updated.

Creating packages

For very big programs, it may be useful to divide the Python code into several directories. There are two things to keep in mind when doing that:

  • To import the package from outside, there needs to be a file __init__.py (it may be empty).
  • The directory with the package needs to be in Pythons search path (see below).

Where Python looks for modules

When importing modules or packages, Python looks in:

  • The current directory.
  • The Python2.6/lib/site-packages folder.
  • Everything in the PYTHONPATH environment variable. In Python, it can be accessed with:
import sys
print sys.path
sys.path.append('my_directory')

import my_package.my_module