[Python-ideas] Why operators are useful

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Mon Mar 18 21:14:28 EDT 2019

On 3/18/19 7:12 PM, Steven D'Aprano wrote:
 > On Mon, Mar 18, 2019 at 06:34:48PM -0500, Dan Sommers wrote:
 >> So how many of you got tired of those three statements and
 >> added something like the following function to your private
 >> collection of useful functions:
 >>     def merged_mappings(mapping, other):
 >>         temp = mapping.copy()
 >>         temp.update(other)
 >>         return temp # no need to del temp here!
 >> turning two or three statements into a simple expression?
 >> I sure didn't.
 > I did, only I called it "updated()".
 > As tends to happen, what started as a three line function quickly
 > became more complex. E.g. docstrings, doctests, taking an arbitrary
 > number of dicts to merge, keyword arguments. The latest version of my
 > updated() function is 12 lines of code and a 13 line docstring, plus
 > blank lines.

Yeah, that happens.  :-)

 > And then I found I could never guarantee that my private toolbox was
 > available, on account of it being, you know, *private*. So I found
 > myself writing:
 > try:
 >      from toolbox import updated
 > except ImportError:
 >      # Fall back to a basic, no-frills version.
 >      def updated(d1, d2):
 >          ...
 > which then means I can't use the extra frills in my private
 > version. So why have the private version when I can't use it?

The fact that you went to the trouble of writing (and testing and
documenting and maintaining) that function, if nothing else, says that
you perform this operation enough that repeating those three lines of
code started to bother you.  That's real evidence that merging mappings
is *not* a once-a-year problem.

To get back to Antoine's question, what are the use cases for
your well-honed library function?  Do you use it in every new
project, or only projects of certain kinds (GUIs, daemons, etc.)?

 > Unless you are only writing for yourself, never to share your code
 > with anyone else, "just put it in your private toolbox" can be
 > impractical.

Depending on the nature of the project, my private toolbox is open in
both directions.  Obviously, I'm not for stealing code from elsewhere
and calling it my own, but I've certainly taken outside ideas and
incorporated them into my private toolbox.  I've also "contributed" bits
and pieces from my private toolbox into other projects; in some ways,
that's just passing folklore and tribal knowledge to the next generation
of programmers.

More information about the Python-ideas mailing list