import hashlib


def hash_reaction(reaction, string_only=False):
    """Generate a unique hash for the metabolites and coefficients of the
    reaction.

    """
    def sorted_mets(reaction):
        return sorted([(m.id, v) for m, v in reaction.metabolites.iteritems()],
                      key=lambda x: x[0])
        
    if string_only:
        hash_fn = lambda s: s
    else:
        hash_fn = lambda s: hashlib.md5(s).hexdigest()

    return hash_fn(''.join(['%s%.3f' % t for t in sorted_mets(reaction)]))