Wednesday, March 4, 2009

Using predicates with the boduch library

The boduch Python library has a new Predicate class that can be used to evaluate predicates. The Predicate class is meant to be an abstract super class. As of the 0.1.2 release of the library, there is only an Equal predicate. This predicate can be used to test the equality of two specified values. For example, consider the following.
#Example; Using the boduch.predicate.Equal predicate.

from boduch.predicate import Equal

if __name__=="__main__":
val1="My Value"
val2="My Value"
while Equal(val1, val2):
print "Changing val1 in order to exit our loop."
val1="Exit"
print val1
In this example, we define two string values; val1 and val2. We then use the Equal predicate as our loop condition. The Equal predicate will always evaluate to true as long as the two specified operators are equal. The Equal predicate uses the == Python operator to evaluate the result. So, why bother with the boduch predicates? One reason would be consistency if you are using the library elsewhere in the application. Another reason may be readability.

The Equal predicate is actually a Python class. Every time we instantiate Equal(), we are actually evaluating against an Equal instance. The equal predicate defines overloaded operators that handle the comparison when the instance is used in that context. There are also events and handles for predicates in the boduch library. If necessary, other handles may subscribe to these events. However, the events published by predicates in the boduch library are atomic. This means that no new threads will be started for these handles.

The next release of the library should have some more interesting predicates such as Greater and Less.

No comments :

Post a Comment