operator module functions

Gelonida N gelonida at gmail.com
Wed Oct 8 23:05:08 CEST 2014


On 10/8/2014 9:09 PM, Terry Reedy wrote:
> On 10/8/2014 6:57 AM, Steven D'Aprano wrote:
>
>> According to the documentation, operator.__add__ is the "official"
>> function,
>> and operator.add is just there for convenience.
>
> You are paraphrasing "The function names are those used for special
> class methods; variants without leading and trailing __ are also
> provided for convenience."  But then there is the following:
>
> 10.3.1. Mapping Operators to Functions
>
> This table shows how abstract operations correspond to operator symbols
> in the Python syntax and the functions in the operator module.
> Operation     Syntax     Function
> Addition     a + b     add(a, b)
>
> etc, using the 'convenient' names. I would like to deprecate and
> eventually remove the dunder names.  To me, the duplication is not
> 'convenient'.
>


I'd be curious about a proposal to obsolete the double underscore 
functions and just keep operator.add or to just keep the operator +

For me they seem rather distinct, though they are interchangable in 
certain situations.

Perhaps I got something wrong, but all dunder functions are 'magic' 
functions. Many of them mostly should ne used when when overloading 
behaviour or when creating a class which should implement operators.

So for implemetation you use __add__ for using you use the operator +
if you need a

class MyClass(object):
         def __init__(self, x, y):
                 self.x = x
                 self.y = y

         # implements + for a certain type
         def __add__(self, other):
                 return MyClass(self.x + other.x, self.y + other.y)

         def __repr__(self):
             return "(%f,%f)" % (self.x, self.y)


a = MyClass(1,2)
b = MyClass(4,5)

print(a)
print(b)
print(a+b)

# operator.add is identical to the + operator ,
# BUT it is a function and can thuss be
# assigned to variables passed as parameter

def dosomething(op, val1, val2):
	return op(val1, val2)

print(dosomething(operator.add, 1, 2))
print(dosomething(operator.add, a, b))










More information about the Python-list mailing list