views:

926

answers:

4

I have a bot in python that allows the users to evaluate mathematical expressions (via a set of safe functions), but I would like to define my own operator. Does python support such a thing?

+9  A: 

no, python comes with a predefined, yet overridable, set of operators.

dfa
+1 for link to the docs.
Kiv
+5  A: 

No, you can't create new operators. However, if you are just evaluating expressions, you could process the string yourself and calculate the results of the new operators.

Zifre
That will probably be my workaround, yes.
Adi
+3  A: 

If you intend to apply the operation on a particular class of objects, you could just override the operator that matches your function the closest... for instance, overriding __eq__() will override the == operator to return whatever you want. This works for almost all the operators.

Sudhir Jonathan
+12  A: 

While technically you cannot define new operators in Python, this clever hack works around this limitation. It allows you to define infix operators like this:

# simple multiplication
x=Infix(lambda x,y: x*y)
print 2 |x| 4
# => 8

# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
print [1,2,3] |isa| []
print [1,2,3] <<isa>> []
# => True
Ayman Hourieh
+1 That hack is pretty cool, but I don't think it will work in this situation.
Zifre
A nice hack and I'm going to give you +1 for it.
Adi
It might be an intersting hack but i don't think that this is good solution. Python does not allow to create own operators, a design decision which was made for a good reason and you should accept it instead of seeing this as a problem and inventing ways around it. It is not a good idea to fight against the language you are writing the code in. If you really want to you should use a different language.
DasIch
@DasIch I couldn't disagree more. We're not all free to chose a language deliberately. On the other side, I don't see why I should settle with anybody else's design decisions if I'm not satisfied. - Excellent hack indeed!
ThomasH