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
2009-05-31 16:03:03
+1 for link to the docs.
Kiv
2009-05-31 18:42:42
+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
2009-05-31 16:06:16
+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
2009-05-31 16:27:43
+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
2009-05-31 18:18:32
+1 That hack is pretty cool, but I don't think it will work in this situation.
Zifre
2009-05-31 18:22:21
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
2009-06-01 22:24:20
@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
2010-09-15 17:10:40