Python – External classes in Python

pythonpython-importpython-module

I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.

Best Solution

About the import statement:

(a good writeup is at http://effbot.org/zone/import-confusion.htm and the python tutorial goes into detail at http://docs.python.org/tutorial/modules.html )

There are two normal ways to import code into a python program.

  1. Modules
  2. Packages

A module is simply a file that ends in .py. In order for python, it must exist on the search path (as defined in sys.path). The search path usually consists of the same directory of the .py that is being run, as well as the python system directories.

Given the following directory structure:

myprogram/main.py
myprogram/rss.py

From main.py, you can "import" the rss classes by running:

import rss
rss.rss_class()

#alternativly you can use:
from rss import rss_class
rss_class()

Packages provide a more structured way to contain larger python programs. They are simply a directory which contains an __init__.py as well as other python files.

As long as the package directory is on sys.path, then it can be used exactly the same as above.


To find your current path, run this:

import sys
print(sys.path)