Overriding logical operators?

Andrew Durdin adurdin at gmail.com
Sun Aug 22 05:31:43 CEST 2004


On Sat, 21 Aug 2004 21:38:01 -0400, Michael J. Fromberger
<michael.j.fromberger at clothing.dartmouth.edu> wrote:
> 
> The implementation of "and" and "or" are special, as others have pointed
> out.  However, you do have some control over how they behave for objects
> of user-defined classes.  By overriding __nonzero_, you can define
> whatever truth value you like for instances of a user-defined class.

I suppose now I ought to say why I need to to do more than that. I've
got a situation where I want to construct an expression, but evaluate
it later when I get more information. I came up with a "DelayedEval"
class, the instances of which can have operations performed on them,
but the result is not evaluated until a particular method is called.
I'm currently overriding all the operators I can, so that these
instances can be handled in a fairly normal fashion for the most part.
For example:

foo = DelayedEval()
foo = (-foo + 15) * 3
foo_positive = (foo >= 0)

print foo.evaluate(10)      # prints 15
print foo.evaluate(20)      # prints -15
print foo_positive.evaluate(10)      # prints True
print foo_positive.evaluate(20)      # prints False

In this situation, merely overriding the __nonzero__ method will not
allow me to delay the evaluation of the logical boolean operators; to
do that I need to be able to override them.

The alternative solution that I can see to the issue is to use lambdas
to create the expressions I need, and calling them to evaluate them,
e.g.:

foo = lambda v: (-v + 15) * 3
foo_positive = lambda v: (foo(v) >= 0)

This will work, but having to manually chain the evaluation in this
way is a little awkward. It also doesn't allow me to print the
expressions. With the DelayedEval class, I can do this:

print foo_positive      # prints  (((-(value) + 15) * 3) >= 0)



More information about the Python-list mailing list