473,769 Members | 4,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proto-PEP: Overloadable Boolean Operators

Discussion is invited on the following proto-PEP.

-------------------------------------------------------------

PEP ??? - Overloadable Boolean Operators
=============== =============== ==========

SUMMARY

This PEP proposes an extension to permit objects to define their own
meanings for the boolean operators 'and', 'or' and 'not', and suggests
an efficient strategy for implementation. A prototype of this
implementation is available for download from:

http://www.cosc.canterbury.ac.nz/~gr...hon_OBO.tar.gz
BACKGROUND

Python does not currently provide any '__xxx__' special methods
corresponding to the 'and', 'or' and 'not' boolean operators. In the
case of 'and' and 'or', the most likely reason is that these operators
have short-circuiting semantics, i.e. the second operand is not
evaluated if the result can be determined from the first operand. The
usual techique of providing special methods for these operators
therefore would not work.

There is no such difficulty in the case of 'not', however, and it
would be straightforward to provide a special method for this
operator. The rest of this proposal will therefore concentrate on
providing a way to overload 'and' and 'or'.

MOTIVATION

There are many applications in which it is natural to provide custom
meanings for Python operators, and in some of these, having boolean
operators excluded from those able to be customised can be
inconvenient. Examples include:

1. Numeric/Numarray, in which almost all the operators are defined on
arrays so as to perform the appropriate operation between
corresponding elements, and return an array of the results. For
consistency, one would expect a boolean operation between two arrays
to return an array of booleans, but this is not currently possible.

There is a precedent for an extension of this kind: comparison
operators were originally restricted to returning boolean results, and
rich comparisons were added so that comparisons of Numeric arrays
could return arrays of booleans.

2. A symbolic algebra system, in which a Python expression is
evaluated in an environment which results in it constructing a tree of
objects corresponding to the structure of the expression.

3. A relational database interface, in which a Python expression is
used to construct an SQL query.

A workaround often suggested is to use the bitwise operators '&', '|'
and '~' in place of 'and', 'or' and 'not', but this has some
drawbacks. The precedence of these is different in relation to the
other operators, and they may already be in use for other purposes (as
in example 1). There is also the aesthetic consideration of forcing
users to use something other than the most obvious syntax for what
they are trying to express. This would be particularly acute in the
case of example 3, considering that boolean operations are a staple of
SQL queries.

REQUIREMENTS

The requirements for a successful solution to the problem of allowing
boolean operators to be customised are:

1. In the default case (where there is no customisation), the existing
short-circuiting semantics must be preserved.

2. There must not be any appreciable loss of speed in the default
case.

3. If possible, the customisation mechanism should allow the object to
provide either short-circuiting or non-short-circuiting semantics, at
its discretion.

One obvious strategy, that has been previously suggested, is to pass
into the special method the first argument and a function for
evaluating the second argument. This would satisfy requirements 1 and
3, but not requirement 2, since it would incur the overhead of
constructing a function object and possibly a Python function call on
every boolean operation. Therefore, it will not be considered further
here.

The following section proposes an implementation that addresses all
three requirements. A prototype of this implementation, in the form of
a patch to Python 2.3, is available from:

http://www.cosc.canterbury.ac.nz/~gr...hon_OBO.tar.gz
PROPOSAL

Special Methods

At the Python level, objects may define the following special methods.

Unary: __not__(self)

Binary, phase 1: __and1__(self) __or1__(self)

Binary, phase 2: __and2__(self, other) __or2__(self, other)
__rand2__(self, other) __ror2__(self, other)

The __not__ method, if defined, implements the 'not' operator. If it
is not defined, or it returns NotImplemented, existing semantics are
used.

To permit short-circuiting, processing of the 'and' and 'or' operators
is split into two phases. Phase 1 occurs after evaluation of the first
operand but before the second. If the first operand defines the
appropriate phase 1 method, it is called with the first operand as
argument. If that method can determine the result without needing the
second operand, it returns the result, and further processing is
skipped.

If the phase 1 method determines that the second operand is needed, it
returns the special value NeedOtherOperan d. This triggers the
evaluation of the second operand, and the calling of an appropriate
phase 2 method.

Processing falls back to existing semantics if at any stage a relevant
special method is not found or returns NotImplemented.

As a special case, if the first operand defines a phase 2 method but
no corresponding phase 1 method, the second operand is always
evaluated and the phase 2 method called. This allows an object which
does not want short-circuiting semantics to simply implement the
relevant phase 2 methods and ignore phase 1.
Bytecodes

The patch adds four new bytecodes, LOGICAL_AND_1, LOGICAL_AND_2,
LOGICAL_OR_1 and LOGICAL_OR_2. As an example of their use, the
bytecode generated for an 'and' expression looks like this:

Jul 18 '05 #1
14 2526
On Sun, 05 Sep 2004 22:48:25 +1200, greg <gr**@cosc.cant erbury.ac.nz> wrote:
Discussion is invited on the following proto-PEP.

-------------------------------------------------------------

PEP ??? - Overloadable Boolean Operators
=============== =============== ==========


If I understand this correctly, then logical operations on instances
of the following class should duplicate the existing behaviour for the
boolean type -- is this correct?

class MyBoolean:
def __init__(self, value):
self._value = value

def __not__(self):
return MyBoolean(not self._value)

def __and1__(self):
if(self._value) :
return NeedOtherOperan d
else:
return self

def __and2__(self, other):
return self

def __or1__(self):
if(self._value) :
return self
else:
return NeedOtherOperan d

def __or2__(self, other):
return self
The PEP doesn't explicitly describe when __rand2__ (or __ror2__) is
used. I'd guess that it will be called for (A and B) when A defines
neither __and1__ nor __and2__ -- is this correct?

Anyway, I'll have to have a close look at your patch -- I'd been
toying with the idea of implementing [or attempting to implement] this
myself.
Jul 18 '05 #2
Andrew Durdin wrote:
If I understand this correctly, then logical operations on instances
of the following class should duplicate the existing behaviour for the
boolean type -- is this correct?

def __and2__(self, other):
return self
That should be

return other

and similarly for __or2__. Otherwise it looks right.
The PEP doesn't explicitly describe when __rand2__ (or __ror2__) is
used. I'd guess that it will be called for (A and B) when A defines
neither __and1__ nor __and2__ -- is this correct?


Not exactly. It will get called whenever the second operand
is needed, the first operand doesn't define __and2__, and the
second operand does define __rand2__.

The exact rules are rather complicated to state completely. I
have some text which spells it all out in mind-numbing detail,
but I left it out of the first draft of the PEP for fear of
scaring people off before I'd got the idea across. Perhaps
I'll include it as an appendix or something.

Greg
Jul 18 '05 #3
Hello greg,
PEP ??? - Overloadable Boolean Operators
=============== =============== ==========
<snip>
Unary: __not__(self)

Binary, phase 1: __and1__(self) __or1__(self)

Binary, phase 2: __and2__(self, other) __or2__(self, other)
__rand2__(self, other) __ror2__(self, other)

<snip>

Why not just __bool__(self) -> True, False?
IMO this will answer all of your needs and will require less changes.

Bye.
--
------------------------------------------------------------------------
Miki Tebeka <mi*********@zo ran.com>
http://tebeka.spymac.net
The only difference between children and adults is the price of the toys
Jul 18 '05 #4
Miki Tebeka wrote:
Hello greg,

PEP ??? - Overloadable Boolean Operators
============= =============== ============
<snip>
Unary: __not__(self)

Binary, phase 1: __and1__(self) __or1__(self)

Binary, phase 2: __and2__(self, other) __or2__(self, other)
__rand2__(self, other) __ror2__(self, other)

<snip>


Why not just __bool__(self) -> True, False?
IMO this will answer all of your needs and will require less changes.


There is already a __nonzero__ special. Presumably more control is
desired.

Jp
Jul 18 '05 #5
Miki Tebeka wrote:

Why not just __bool__(self) -> True, False?
IMO this will answer all of your needs and will require less changes.


Have you read any of the rationale in the PEP?
The whole reason for this is that overriding __bool__
is *not* sufficient for the use cases I have
in mind.

Greg

Jul 18 '05 #6
greg <gr**@cosc.cant erbury.ac.nz> wrote:
...
Python does not currently provide any '__xxx__' special methods
corresponding to the 'and', 'or' and 'not' boolean operators. In the ... There is no such difficulty in the case of 'not', however, and it


Indeed, that's what the strangely-named __nonzero__ special method does:
it's invoked upon the 'not' operator and in no other case, so it would
be strange to claim it's anything but "a special method corresponding to
the 'not' boolean operator". Problem is, __nonzero__ is currently
typechecked -- it has to return an integer. Maybe relaxing that
constraint might be enough for 'not' (while your elaborate proposals may
well be necessary for 'and' & 'or').
Alex
Jul 18 '05 #7
al*****@yahoo.c om (Alex Martelli) writes:
greg <gr**@cosc.cant erbury.ac.nz> wrote:
...
Python does not currently provide any '__xxx__' special methods
corresponding to the 'and', 'or' and 'not' boolean operators. In the

...
There is no such difficulty in the case of 'not', however, and it


Indeed, that's what the strangely-named __nonzero__ special method does:
it's invoked upon the 'not' operator and in no other case,


Erm. No.
class C(object): .... def __nonzero__(sel f):
.... print 'hi!'
.... return 1
.... if C(): pass

....
hi!

Or do I misunderstand what you're saying?

Cheers,
mwh

--
Arrrrgh, the braindamage! It's not unlike the massively
non-brilliant decision to use the period in abbreviations
as well as a sentence terminator. Had these people no
imagination at _all_? -- Erik Naggum, comp.lang.lisp
Jul 18 '05 #8
Michael Hudson <mw*@python.net > wrote:
al*****@yahoo.c om (Alex Martelli) writes:
greg <gr**@cosc.cant erbury.ac.nz> wrote:
...
Python does not currently provide any '__xxx__' special methods
corresponding to the 'and', 'or' and 'not' boolean operators. In the

...
There is no such difficulty in the case of 'not', however, and it


Indeed, that's what the strangely-named __nonzero__ special method does:
it's invoked upon the 'not' operator and in no other case,


Erm. No.
class C(object): ... def __nonzero__(sel f):
... print 'hi!'
... return 1
... if C(): pass

...
hi!

Or do I misunderstand what you're saying?


Oops, no, you're right, I was wrong -- not sure why I had that
misconception in my mind right now...
Alex
Jul 18 '05 #9
Alex Martelli wrote:
Problem is, __nonzero__ is currently
typechecked -- it has to return an integer.


Yes, that's the problem. I should probably elaborate
on that a bit in the PEP.

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3261
by: fedor | last post by:
Hi all, happy new year, I was trying to pickle a instance of a subclass of a tuple when I ran into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should I rewrite my class so I can pickle it? Thanks , Fedor
10
3153
by: x2164 | last post by:
hi all, Linux 2.4.28 Glibc 2.2.5 gcc 2.95.3 I'm new to Python. I've compiled Python 2.4 from tar file.
3
2120
by: Earl Eiland | last post by:
I'm trying to process the IP packet length field, as recorded by pcap (Ethereal) and recovered using pcapy. When I slice out those bytes, I get a value that shows in '\x00' format, rather than '0x00'. Neither int() nor eval() are working. How do I handle this? Earl Eiland
35
3682
by: Troll | last post by:
Hi, I need to write a script which reads some data and reports the findings. Just to give you an idea the structure is similar to the following. Data input example: HEADING 1 ********** ColumnA ColumnB ColumnC ColumnD ColumnE
3
2525
by: Philippe Guglielmetti | last post by:
Look at these few lines of code: class A { public: virtual void f() { cout << "A";}}; class B : public A{public: static void f() { cout << "B"; }}; class C : public B{public: void f() { cout << "C"; }}; // virtual or not ? that's the question... int main(int, char**) { A* x; A a; B b; C c;
2
3895
by: Jackson Yap | last post by:
can someone kind enough to help me look at the attached html and js file? Why is it that the javascript menu could not work at www.apchosting.net but could work at http://home.pacific.net.sg/~jacksony ? (the drop down bar could not work at www.apchosting.net but can drop at home.pacific.net.sg. I suspect it is a server problem but was told it is not possible, therefore assuming it is a client script problem? the script works last time...
8
2036
by: Geoff Cox | last post by:
Hello, When using Internet Explorer, on networked PCs in a college, to view a page of mine with Javascript code in it the "stack overflow" error message appears. When I access the same file from my home PC no such message. Is it possible for this to be caused by any IE setting?
2
1375
by: ian | last post by:
Hi; What is void daily_log(char *, ...); saying, the 3 periods? Regards Ian
0
1223
by: Neil Cerutti | last post by:
I'm a royal n00b to writing translators, but you have to start someplace. In my Python project, I've decided that writing the dispatch code to sit between the Glulx virtual machine and the Glk API will be best done automatically, using the handy prototypes. Below is the prototype of the lexer, and I'd like some comments in case I'm doing something silly already.
2
1832
by: Hal Vaughan | last post by:
I have a file where I'm putting a lot of variable definitions. Some of them will be maps that include references to functions. This file will be processed (by include) before other files are processed. If I put protofunction definitions in this definition file and the actual functions in another file, are there any non-obvious consequences to this? Thanks! Hal
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9848
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7392
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6661
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5293
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3947
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3551
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.