6.1 Looping over the Atoms and Bonds of a Molecule

The Python wrapper to OEChem provides generator methods for traversing the atoms and bonds in a molecule. Since the underlying storage mechanism is not exposed, there is no longer the notion of an array of atoms or and array of bonds inside a molecule. In order to traverse the atoms or bonds in C++, one uses iterators, but in Python we have wrapped the C++ iterators into generator methods much like the loop over molecules in a oemolistream or tag,value pairs of SD data.

The two methods are GetAtoms() and GetBonds(). For each successive iteration through the for loop, these methods return the next atom and bond respectively.

The following example show how to traverse the atoms and print out their atomic numbers and then traverse the bonds and print their bond order.

#!/usr/bin/env python
# ch6-1.py
from openeye.oechem import *

mol = OEGraphMol()
OEParseSmiles(mol, "c1ccccc1")

print "atoms"
for atom in mol.GetAtoms():
    print atom.GetAtomicNum()
print "bonds"
for bond in mol.GetBonds():
    print bond.GetOrder()

Note that this example also introduces a couple of new methods, an OEAtomBase member function: GetAtomicNum() and an OEBondBase member function: GetOrder(). These and other member functions of these two classes will be covered in more detail in subsequent chapters.