[Baypiggies] overriding boolean and,or operators?

Brent Pedersen bpederse at gmail.com
Mon Jul 12 23:14:20 CEST 2010

On Mon, Jul 12, 2010 at 11:21 AM, Stephen Lacy <slacy at slacy.com> wrote:
> Hi,
> According to http://docs.python.org/library/operator.html boolean operators
> ==, <, >, etc. can be overridden via __eq__(), __lt__(), __gt__(), etc.
> They also mention *bitwise* and/or operators via __and__() and __or__().
> But, I'd like to override the *boolean* operators 'and' and 'or'.  Is this
> possible?
> Background:
> I'm experimenting with a library that takes a python expression like this:
> "(a == b) or (c and d)"
> And instead of evaluating it via the interpreter, creates (and returns) a
> representation of said boolean decision tree such that it can be evaluated
> dynamically and/or converted to some other form, like prefix or postfix
> (this is just an example and for my own exploration and deeper understanding
> of operator overrides).
> I can get this to work if I use the syntax "(a == b) | (c & d)" but I would
> prefer to use the more pythonic and syntactically correct "and" and "or".
> Is this possible?
> Steve
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies

not quite sure i follow your use-case, but...
you can also override __nonzero__ which i think is what gets called
when you use bool(),
but you'll probably still need a bit more, you can add some sugar using this:

so you'd have your classes implement __bool_or__ (or whatever you want
to call it) and then use:

OR = Infix(lambda a, b: a.__bool_or__(b))

MyClass(22) |OR| MyClass(0)

where MyClass implements __bool_or__


More information about the Baypiggies mailing list