Pages

Monday, 5 September 2011

How to share Python code with PyDev for Eclipse

Python allows sharing the code between projects. Shared code (classes, functions,...) is grouped by its purpose/nature into modules which are imported into projects. Modules are simple text files containing Python code and they have extension .py.Modules are organized into packages. Package is actually a directory which contains __init__.py file, modules and/or other packages.

Packages/modules are usually added as subdirectories of src directory. If any other Python project wants to use any package from this project, it needs to add absolute path to common\src to its PYTHONPATH.

File->New->PyDev Package

This wizard forces us to pick src folder in some project as Source Folder:
Source Folder: /common/src
Name: util

A new directory - util - has been created and file __init__.py has been automatically added to it. It is empty by default and we can leave it as such. This file marks its parent directory (util) as Python package directory.

Let us create now a new Python project (named md5) which uses get_md5 function from util.crypto module:

File->New->PyDev Project, Name: md5. We now need to add path to desired module to PYTHONPATH for this project: select project name in the Navigator pane; right-click, Properties; select PyDev - PYTHONPATH; select "External Libraries" tab (as we're adding source that does not belong to this workspace); click on "Add source folder" and browse to the common\src directory (e.g. "C:\Users\Bojan\workspace\Python\common\src").