[Python-ideas] Discourage operator.__dunder__ functions

Todd toddrjen at gmail.com
Wed Apr 19 08:54:07 EDT 2017


On Apr 13, 2017 14:25, "Steven D'Aprano" <steve at pearwood.info> wrote:

Notice that I said *discourage* rather than *deprecate*.

Quoting the documentation:

    The operator module exports a set of efficient functions
    corresponding to the intrinsic operators of Python. For
    example, operator.add(x, y) is equivalent to the expression
    x+y. The function names are those used for special class
    methods; variants without leading and trailing __ are also
    provided for convenience.

https://docs.python.org/3/library/operator.html

I propose four simple documentation changes, and no code change:


(1) The quoted paragraph is factually wrong to say:

    "The function names are those used for special class methods"

    We can fix that by changing it to:

    "Some function names are those used for special class methods".


(2) Replace the word "convenience" in the quoted paragraph by
    "backward compatibility";


(3) Add a note close to the top of the page that the non-dunder
    names are preferred for new code.


(4) And a note stating that existing dunder functions will
    remain, but no new ones will be added.


The existing dunder names will remain aliases to the non-dunder names;
they will not be deprecated (maybe in Python 5000 *wink*). Those who
really want to use them can continue to do so.

Regarding point (1) above:

- Not all operator functions have a dunder alias.

- The dunder functions don't always correspond to a dunder method. For
example, there is operator.__concat__ for sequence concatenation, but no
str.__concat__ or list.__concat__ methods.

- Even when the dunder function corresponds by name to the dunder
method, they don't mean the same thing. For example, operator.__add__ is
*not* the same as just calling the first argument's __add__ method.

- And finally, I fail to see how having to type an extra four characters
is a "convenience".


Long ago, when the operator module was first introduced, there was a
much stronger correspondence between the operator.__dunder__ functions
and dunder methods. But I think that correspondence is now so weak that
we should simply treat it as a historical artifact.


What about going a step further and moving the __dunder__ functions to
another section?

Perhaps it could have a statement saying that some of the functions also
come in dunder versions, but that people are encouraged to use the regular
version. Then you can just have a table with the normal version on the left
and the equivalent dunder version (if any) on the right.

This would also have the benefit of making the existing function list
simpler and clearer.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170419/b4a548ba/attachment.html>


More information about the Python-ideas mailing list