operator module functions

Ben Finney ben+python at benfinney.id.au
Wed Oct 8 17:57:15 EDT 2014


random832 at fastmail.us writes:

> On Wed, Oct 8, 2014, at 15:38, Ethan Furman wrote:
> > The main reason I bother using the operator module is for the
> > readability of not seeing the dunders, and the writability of not
> > having to type them.
>
> I'm not sure what situation you would have to type them (as opposed to
> simply a + b) that the operator module would help with.

Any situation where you need to refer to a function. ‘+’ is not a
function, whereas ‘operator.add’ is.

    import operator
    import functools

    add_three = functools.partial(operator.add, 3)

    foo = list(range(10))
    bar = map(add_three, foo)

The above ‘map’ invocation – which is useful because it allows any
arbitrary one-parameter function to be used – cannot be used with ‘+’,
which is not a function.

Likewise, ‘functools.partial’ requires a function, and ‘+’ is not a
function.

There are countless such uses for the functions in the ‘operator’
module.

-- 
 \      “It is the integrity of each individual human that is in final |
  `\        examination. On personal integrity hangs humanity's fate.” |
_o__)               —Richard Buckminster Fuller, _Critical Path_, 1981 |
Ben Finney




More information about the Python-list mailing list