Packaging an Extension

Chimera extensions typically can be divided into two parts: data manipulation and user interface. For example, the code in Toolbar Buttons defines a function which changes the display status of some atoms (the data manipulation code) and then creates a toolbar button that invokes the function when pressed (the user interface code). The data manipulation code often may be reused when building a new extension, but the user interface code typically is not needed. Separating the parts into multiple source files simplifies reusing the data manipulation code, but complicates managing the extension code as a unit. Fortunately, Python supports the package concept for just such a situation.

A Python package consists of a set of modules (.py files) stored in the same directory in the file system. One of the modules must be named, which is the initialization module that is automatically executed when the package is imported. By convention, Chimera extension packages implement the data manipulation code in and the user interface code in a module named Implementors of new functionality can access the data manipulation code by:

import extension

and end users can display the user interface by:

import extension.gui

where extension is the name of the package. The code in Toolbar Buttons is divided in such a manner below:

Example ToolbarButtonPackage/

The contents of ToolbarButtonPackage/ is identical to the first section of code in Toolbar Buttons.

def mainchain():

import re
from chimera import openModels, Molecule

mainChain = re.compile("^(N|CA|C)$", re.I)
for m in openModels.list(modelTypes=[Molecule]):
for a in m.atoms:
a.display = mainChain.match( != None

Example ToolbarButtonPackage/

The contents of ToolbarButtonPackage/ is similar to the last section of code in Toolbar Buttons, with the exception that the mainchain function is now referenced as ToolbarButtonPackage.mainchain. The reason for the change is that is a submodule, while the mainchain function is in the main package. Since a submodule cannot directly access items defined in the main package, must first import the package import ToolbarButtonPackage and refer to the function by prepending the package name (ToolbarButtonPackage.mainchain in the call to

import chimera
import ToolbarButtonPackage'ToolbarButton.tiff', ToolbarButtonPackage.mainchain, 'Show Main Chain', None)

Running the Example

The example code files must be saved in a directory named ToolbarButtonPackage. To run the example, start chimera, bring up the Tools preference category (via the Preferences entry in the Favorites menu; then choosing the "Tools" preference category) and use the Add button to add the directory above the ToolbarButtonPackage directory. Then type the following command into the IDLE command line:

import ToolbarButtonPackage.gui

The effect should be identical to running the Toolbar Buttons example.