[Python-ideas] Why operators are useful
Steven D'Aprano
steve at pearwood.info
Mon Mar 18 20:12:52 EDT 2019
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.
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?
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.
--
Steven
More information about the Python-ideas
mailing list