473,789 Members | 2,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

user-defined operators: a very modest proposal

I have been studying Python recently, and I read a comment on one
web page that said something like "the people using Python for heavy math
really wish they could define their own operators". The specific
example was to define an "outer product" operator for matrices. (There
was even a PEP, number 211, about this.)

I gave it some thought, and Googled for previous discussions about this,
and came up with this suggestion:

User-defined operators could be defined like the following: ]+[

I'm not any kind of language design expert, but this seems to me like a
syntax that would be easy for Python to recognize. Because the square
braces are reversed from the usual "[]" order, this should not look like
any currently-valid code. And square braces, IMHO, do not fail the
"low-toner printout" test. (Some earlier proposals included operators like
"~+" and these were deemed too hard to read.)

For improved readability, Python could even enforce a requirement that
there should be white space on either side of a user-defined operator.
I don't really think that's necessary.

It should be possible to define operators using punctuation,
alphanumerics, or both:

]+[
]add[
]outer*[
Examples of use:

m = m0 ]*[ m1
m = m0]*[m1

m = m0 ]outer*[ m1
m = m0]outer*[m1

It looks a lot better with the white space, I think, but it's not horrible
without the white space.
Also, there should be a way to declare what kind of precedence the user-defined
operators use. Python already has lots of operators with different precedence,
and I think the best way is just to indicate which Python operator the new
operator's precedence should match:

class MyExcellentMatr ix(object):
@precedence('*' )
def __op_outer*__(s elf, right):
# ...do stuff...

I think a decorator is a good way to set the precedence.
Perhaps the default precedence should be that of '+'.

Augmented forms should be supported:

]+=[
]*=[
]outer*=[
Examples:

m ]*=[ m0
m]*=[m0

m ]outer*=[ m0
m]outer*=[
Either I actually have made a sensible suggestion, or else people will now
explain why this idea isn't good (and I'll learn something). Either way,
I look forward to your comments.

References:

Elementwise/Objectwise Operators
http://www.python.org/peps/pep-0225.html
Adding A New Outer Product Operator
http://www.python.org/peps/pep-0211.html
--
Steve R. Hastings "Vita est"
st***@hastings. org http://www.blarg.net/~steveha
Nov 22 '05 #1
17 2445
On Tue, 22 Nov 2005 13:48:05 -0800, Steve R. Hastings wrote:
User-defined operators could be defined like the following: ]+[
[snip]
Examples of use:

m = m0 ]*[ m1
m = m0]*[m1
That looks to me like multiplying two lists. I have to look twice to see
that the operands are merely m0 and m1 and not [m0] and [m1].
m = m0 ]outer*[ m1
m = m0]outer*[m1


That just looks weird.
Here is a thought: Python already supports an unlimited number of
operators, if you write them in prefix notation:

inner_product(m 0, m1)
outer_product(m 0, m1)
etc.

Here is some syntax that I don't object to, although that's not saying
much. In mathematics, there are operators of a plus sign within a circle,
multiply sign within a circle, etc. The closest we can get in plain ASCII
would be:

m0(+)m1
m0(*)m1
m0(-)m1
etc.
--
Steven.

Nov 22 '05 #2
If your proposal is implemented, what does this code mean?
if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation'
Since it contains ']+[' I assume it must now be parsed as a user-defined
operator, but this code currently has a meaning in Python.

(This code is the first example I found, Python 2.3's test/test_types.py, so it
is actual code)

I don't believe that Python needs user-defined operators, but let me share my
terrible proposal anyway: Each unicode character in the class 'Sm' (Symbol,
Math) whose value is greater than 127 may be used as a user-defined operator.
The special method called depends on the ord() of the unicode character, so
that __u2044__ is called when the source code contains u'\N{FRACTION SLASH}'.
Whatever alternate syntax is adopted to allow unicode identifier charactersto
be typed in pure ASCII will also apply to typing user-defined operators. "r"
and "i" versions of the operators will of course exist, as in __ru2044__ and
__iu2044__.

Also, to accomodate operators such as u'\N{DOUBLE INTEGRAL}', which are not
simple unary or binary operators, the character u'\N{NO BREAK SPACE}' will be
used to separate arguments. When necessary, parentheses will be added to
remove ambiguity. This leads naturally to expressions like
\N{DOUBLE INTEGRAL} (y * x**2) \N{NO BREAK SPACE} dx \N{NO BREAK SPACE} dy
(corresponding to the call (y*x**2).__u222 c__(dx, dy)) which are clearly easy
to love, except for the small issue that many inferior editors will not clearly
display the \N{NO BREAK SPACE} characters.

Some items on which I think I'd like to hear the community's ideas are:
* Do we give special meaning to comparison characters like
\N{NEITHER LESS-THAN NOR GREATER-THAN}, or let users define them in new
ways? We could just provide, on object,
def __u2279__(self, other): return not self.__gt__(oth er) and other.__gt__(se lf)
which would in effect satisfy all users.

* Do we immediately implement the combination of operators with nonspacing
marks, or defer it? If we implement it, do we allow the combination with
pure ASCII operators, as in
u'\N{COMBINING LEFT RIGHT ARROW ABOVE}+'
or treat it as a syntax error? (BTW the method name for this would be
__u20e1u002b__, even though it might be tempting to support __u20e1x2b__,
__u2oe1add__ and similar method names) How and when do we normalize
operators combined with more than one nonspacing mark?

* Which unicode operator methods should be supported by built-in types?
Implementing __u222a__ and __iu222a__ for sets is a no-brainer,
obviously, but what about __iu2206__ for integers and long?

* Should some of the unicode mathematical symbols be reserved for literals?
It would be greatly preferable to write \u2205 instead of the other proposed
empty-set literal notation, {-}. Perhaps nullary operators could be defined,
so that writing \u2205 alone is the same as __u2205__() i.e., callingthe
nullary function, whether it is defined at the local, lexical, module, or
built-in scope.

* Do we support characters from the category 'So' (symbol, other)? Not
doing so means preventing programmers from using operators like
\u"n{HEAVY CONCAVE-POINTED BLACK RIGHTWARDS ARROW}". Who are we to
make those kinds of choices for our users?

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDg6EaJd0 1MZaTXX0RAn8NAJ 0enTxrgz3KAS1ot CMHFFDYkSKeQQCg mtyV
OvbivR1dPtSaT2+ bAMjK4jg=
=rK5l
-----END PGP SIGNATURE-----

Nov 22 '05 #3
Steve R. Hastings wrote:
I have been studying Python recently, and I read a comment on one
web page that said something like "the people using Python for heavy math
really wish they could define their own operators". The specific
example was to define an "outer product" operator for matrices. (There
was even a PEP, number 211, about this.)

I gave it some thought, and Googled for previous discussions about this,
and came up with this suggestion:

User-defined operators could be defined like the following: ]+[

I'm not any kind of language design expert, but this seems to me like a
syntax that would be easy for Python to recognize. Because the square
braces are reversed from the usual "[]" order, this should not look like
any currently-valid code.
Is [a,b]+[c] the concatenation of two lists, or a single two-element
list containing a and b ]+[ c?
And square braces, IMHO, do not fail the "low-toner printout" test.


They do. Just yesterday I printed some code in which some of the
square braces didn't show up.

Nov 22 '05 #4
"Steve R. Hastings" <st*****@localh ost.localdomain > writes:
I have been studying Python recently, and I read a comment on one
web page that said something like "the people using Python for heavy math
really wish they could define their own operators". The specific
example was to define an "outer product" operator for matrices. (There
was even a PEP, number 211, about this.)
I gave it some thought, and Googled for previous discussions about this,
and came up with this suggestion:
User-defined operators could be defined like the following: ]+[


See <URL:
http://aspn.activestate.com/ASPN/Coo.../Recipe/384122 > for
some better suggestions, including an implementation in Python.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Nov 23 '05 #5
> Here is a thought: Python already supports an unlimited number of
operators, if you write them in prefix notation:
And indeed, so far Python hasn't added user-defined operators because this
has been adequate.

Here is some syntax that I don't object to, although that's not saying
much. m0(+)m1


That form was discussed previously, as were "[+]", "<+>", etc. The
favorite was "{+}". I believe such forms were considered hard to tell
from code. In particular, m0(+) looks like a function call.

See the PEP:

http://www.python.org/peps/pep-0225.html

Alas, the links to the discussion about this don't work. But it is
possible to use the Google Groups archive of comp.lang.pytho n to read some
of the discussion.
--
Steve R. Hastings "Vita est"
st***@hastings. org http://www.blarg.net/~steveha

Nov 23 '05 #6
> if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation'
Since it contains ']+[' I assume it must now be parsed as a user-defined
operator, but this code currently has a meaning in Python.


Yes. I agree that this is a fatal flaw in my suggestion.

Perhaps there is no syntax that can be done inside the bounds of ASCII
that will please everyone and not break existing code.
Your suggestion of Unicode makes a lot of sense. There are glyphs for
math operators, and if Python can accept Unicode source files, that seems
to me like a much better solution than hacks involving ASCII characters.

I didn't notice it before, but PEP 263 allows Python source files to be
Unicode:

http://www.python.org/peps/pep-0263.html

So the latest versions of Python already have support for Unicode source
files!
Could such Unicode sources be exported to ASCII for porting code to
platforms that don't allow Unicode Python files? Yes: just replace the
Unicode character with a symbol like __op__, where op is the operator.

Actually, that's a better syntax than the one I proposed, too:

__+__
# __add__ # this one's already in use, so not allowed
__outer*__
--
Steve R. Hastings "Vita est"
st***@hastings. org http://www.blarg.net/~steveha

Nov 23 '05 #7
On Tue, Nov 22, 2005 at 04:08:41PM -0800, Steve R. Hastings wrote:
Actually, that's a better syntax than the one I proposed, too:

__+__
# __add__ # this one's already in use, so not allowed
__outer*__


Again, this means something already.
__ = 3
__+__ 6 __outer = 'x'
__outer*__

'xxx'

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDg74ZJd0 1MZaTXX0RAtDAAJ 9pMXaY8ybWaCznI QgR4N4xHISDcQCf aFJw
yAbNACnP5Tx2wGO 6jJE7UXU=
=7jGl
-----END PGP SIGNATURE-----

Nov 23 '05 #8
On Tue, 22 Nov 2005, Steve R. Hastings wrote:
User-defined operators could be defined like the following: ]+[
Eeek. That really doesn't look right.

Could you remind me of the reason we can't say [+]? It seems to me that an
operator can never be a legal filling for an array literal or a subscript,
so there wouldn't be ambiguity.

We could even just say that [?] is an array version of whatever operator ?
is, and let python do the heavy lifting (excuse the pun) of looping it
over the operands. [[?]] would obviously be a doubly-lifted version.
Although that would mean[*] is a componentwise product, rather than an
outer product, which wouldn't really help you very much! Maybe we could
define {?} as the generalised outer/tensor version of the ? operator ...
For improved readability, Python could even enforce a requirement that
there should be white space on either side of a user-defined operator. I
don't really think that's necessary.
Indeed, it would be extremely wrong - normal operators don't require that,
and special cases aren't special enough to break the rules.

Reminds me of my idea for using spaces instead of parentheses for grouping
in expressions, so a+b * c+d evaluates as (a+b)*(c+d) - one of my worst
ideas ever, i'd say, up there with gin milkshakes.
Also, there should be a way to declare what kind of precedence the
user-defined operators use.


Can't be done - different uses of the same operator symbol on different
classes could have different precedence, right? So python would need to
know what the class of the receiver is before it can work out the
evaluation order of the expression; python does evaluation order at
compile time, but only knows classes at execute time, so no dice.

Also, i'm pretty sure you could cook up a situation where you could
exploit differing precedences of different definitions of one symbol to
generate ambiguous cases, but i'm not in a twisted enough mood to actually
work out a concrete example!

And now for something completely different.

For Py4k, i think we should allow any sequence of characters that doesn't
mean something else to be an operator, supported with one special method
to rule them all, __oper__(self, ator, and), so:

a + b

Becomes:

a.__oper__("+", b)

And:

a --{--@ b

Becomes:

a.__oper__("--{--@", b) # Euler's 'single rose' operator

Etc. We need to be able to distinguish a + -b from a +- b, but this is
where i can bring my grouping-by-whitespace idea into play, requiring
whitespace separating operands and operators - after all, if it's good
enough for grouping statements (as it evidently is at present), it's good
enough for expressions. The character ']' would be treated as whitespace,
so a[b] would be handled as a.__oper__("[", b). Naturally, the . operator
would also be handled through __oper__.

Jeff Epler's proposal to use unicode operators would synergise most
excellently with this, allowing python to finally reach, and even surpass,
the level of expressiveness found in languages such as perl, APL and
INTERCAL.

tom

--
I DO IT WRONG!!!
Nov 23 '05 #9
Tom Anderson wrote:
Jeff Epler's proposal to use unicode operators would synergise most
excellently with this, allowing python to finally reach, and even surpass,
the level of expressiveness found in languages such as perl, APL and
INTERCAL.

tom

What do you mean by unicode operators? Link?
Nov 23 '05 #10

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

Similar topics

3
4143
by: zlst | last post by:
Many technological innovations rely upon User Interface Design to elevate their technical complexity to a usable product. Technology alone may not win user acceptance and subsequent marketability. The User Experience, or how the user experiences the end product, is the key to acceptance. And that is where User Interface Design enters the design process. While product engineers focus on the technology, usability specialists focus on the user...
6
11301
by: martin | last post by:
Hi, I am a web page and a web user control. My web user control is placed in my web page using the following directive <%@ Register TagPrefix="uc1" TagName="Header" Src="WebControls/Header.ascx" %> The web user control contains the following server controls
1
7588
by: Shourie | last post by:
I've noticed that none of the child controls events are firing for the first time from the dynamic user control. Here is the event cycle. 1) MainPage_load 2) User control1_Load user clicks a dropdown in UC1 _________________________ 1) MainPage_Load 2) User Control_1 Load
7
2919
by: jsale | last post by:
I'm currently using ASP.NET with VS2003 and SQL Server 2003. The ASP.NET app i have made is running on IIS v6 and consists of a number of pages that allow the user to read information from the database into classes, which are used throughout the application. I have made class collections which, upon reading from the DB, create an instance of the class and store the DB values in there temporarily. My problem is that if user1 looks at...
2
4823
by: rn5a | last post by:
Assume that a user control (MyUC.ascx) encapsulates 2 TextBoxes with the IDs 'txt1' & 'txt2' respectively. To use this user control in an ASPX page, the following Register directive will be required: <%@ Register TagPrefix="UC" TagName="MyUserCtrl" Src="MyUC.ascx" %> Assuming that the ASPX page doesn't use a code-behind, I can access the properties, events etc. of the user control in the ASPX page in this way (assume that the ASPX page...
1
1974
by: Carlettus | last post by:
Dear All, sorry but I'm not sure if this is the right place to post my problem. I was using the following asp code to create users in Active Directory. Suddenly, and I don't know the reason, users are created but the account is disabled (see the flag User.AccountDisabled = False ). There is also another problem even if the user does not exist , the application returns to me with the message that the user already exist. Thank you for...
0
3235
by: rbukkara | last post by:
Hi, I have got the following error while trying to add a user in the LDAP Directory. javax.naming.NameNotFoundException: ; remaining name 'uid=vassila,ou=People,dc=cs,dc=uno,dc=edu' I have given all the attributes which are needed, for the user, in the code and also the proper path where the user has to be added. Please have a look at my code CODE] // This is a class file which stores all the info required for the user
9
6282
by: Gordon | last post by:
I want to add a feature to a project I'm working on where i have multiple users set up on my Postgres database with varying levels of access. At the bare minimum there will be a login user who only has read access to the users table so that users can log in. Once a user has been logged in successfully I want to escalate that user's access level to one appropriate to their role, which will include switching the postgres user they are...
14
3269
by: chromis | last post by:
Hi, I've been trying to implement a more OOP oriented approach to dealing with user security on one of my websites, and I am trying to validate the user against an array of roles, however I am struggling with a type error: The argument ROLES passed to function setRoles() is not of type array. If the component name is specified as a type of this argument, the reason for this error might be that a definition file for such component...
3
2520
by: shapper | last post by:
Hello, On my web site I have a property, Visitor, which is available for Anonymous users: public class Visitor { public CultureInfo Culture { get; set; } public List<GuidPolls { get; set; } }
0
9665
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
10408
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10199
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
10139
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,...
1
7529
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
6768
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
5417
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
4092
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
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.