2

In order to make Python look more familiar, I've tried to assign an operator symbol to a variable's name,just for educational purposes: import operator equals = operator.eq This seems to work fine for equals(a,b) but not for a equals b

Is there a way to express that a equals b instead of a == b

3 Answers3

4

No, Python (and most mainstream languages) does not allow this kind of customization. In Python the restriction is quite intentional — an expression such as a equals b would look ungrammatical to any reader familiar with Python.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
1

Not necessarily, but another SO answer shows how you can use this simple trick to "create" new operators. However, they only work if you surround the operator by | | or by << >>:

equals = Infix(lambda x, y: x == y):
print 2 |equals| 2 # True
Community
  • 1
  • 1
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
0

The best you can do is

def equals(a,b):
    return a == b

equals(1,5)
>> False

or

class my:
value = 0
def equals(self, b):
    return self.value == b

a = my()

a.equals(3)
>>False

But you should use the built-in operator for readability. This way, a reader can distinguish, at once, an operator, a function, a symbol (a variable), a member function, etc...

mbowden
  • 687
  • 6
  • 7
  • You could, however, write the script your way and then use another script to replace equals with =. But I don't recommend that. – mbowden Nov 11 '17 at 06:24