21.1 Callbacks

Simply stated, predicate functors (boolean functors) are functions which return "true" or "false". In OEChem, these functors are often passed into another function. The functors are then called from inside the second function. This is the concept of a "callback" because the second function provides the argument and "call's back" to the functor which was passed into the function. We've already seen examples of this for the generator methods like GetAtoms and GetBonds. However, you can write your own functions and pass predicates as a function argument.

#!/usr/bin/env python
# ch21-1.py

from openeye.oechem import *

def Count(fcn, mol):
    count=0
    for atom in mol.GetAtoms():
        if fcn(atom)==1:
            count += 1
    return count

mol = OEGraphMol()
OEParseSmiles(mol, "c1c(O)c(O)c(Cl)cc1CCCBr")

print "Number of Oxygens = ", Count(IsOxygen(), mol)
print "Number of Carbons = ", Count(HasAtomicNum(6), mol)
print "Number of Halides = ", Count(IsHalide(), mol)

In the example above, the function Count loops over the atom and performs a callback to the predicate functor fcn for each atom. If the predicate returns true, a counter is incremented. The main loop passes three of OEChem's predefined atom predicates to the Count function, allowing the same function to calculate the number atoms in the molecule which satisfy the functor passed to it.