Overriding logical operators?

Robert Brewer fumanchu at amor.org
Sun Aug 22 00:42:24 EDT 2004


Andrew Durdin wrote:
> 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,

Having written all four alternatives (which you're going to write ;),
you
also have the options of:

1) Using & and | instead of 'and' and 'or'. In this way, you can
override within the class in the same maneer you do for gt, lt, etc.
2) Bytecode hacks.

A fairly useful implementation of the latter (which I wrote and use
regularly in my ORM) is available at http://www.aminus.org/rbre/python
as 'logic.py'. It's in the public domain--steal it if you want. If you
really, really want an implementation of the former, I can probably dig
one up.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list