4 ms·
I don't know why operators are the way they are in Python, but to me it looks like an oversight, which ultimately let to the "operator" module, exposing all ope
by Felk 8y ago
I don't know why operators are the way they are in Python, but to me it looks like an oversight, which ultimately let to the "operator" module, exposing all operators as functions
- guitarbill 8y agoAt the risk of oversimplifying/getting the subtleties wrong, operators are syntactic sugar to call magic methods. You could still call the magic method itself: >>> a = 1 >>> a.__add__(2) 3 >>> b = [] >>> b.__len__() 0 It's rare I have to use the "operator" module, and I find Python pretty well thought out w.r.t. consistency. All in all, seems fine to me.
- chriswarbo 8y ago> You could still call the magic method itself Only if you have the first argument available. As a silly example, we might want to do the following (in analogy to the built-in `sum` function): product = lambda vals: reduce(operators.__mult__, vals, 1) We can't use a bound `__mult__` method for situations like this. More generally, looking up methods from particular objects forces our code to be "first order", i.e. we have to explicitly deal with intermediate results which don't appear in higher-order programming. For the `product` case we could do: def product(vals): result = 1 for val in vals: result *= val return result 3/5 of these lines deal with `result`, which doesn't appear at all in the `reduce` version. The same thing happens with stuff like composition too, e.g. the `x` in `lambda x: foo(bar(x))` when we could just `compose(foo, bar)`. When code is bound up in methods, we're often forced to expose these intermediate values, in order to call their methods. Of course, we can abstract over such boilerplate too, with functions like `lambda o, m: o.__getattribute__(m)`, etc. but at that point we're fighting against the language. PS: Yes, I know Guido doesn't like `reduce` and moved it out into `functools` for Python 3.