[Python-ideas] Make partial a built-in
Nick Coghlan
ncoghlan at gmail.com
Wed Sep 21 12:15:08 EDT 2016
On 21 September 2016 at 02:42, Ryan Gonzalez <rymg19 at gmail.com> wrote:
> Most often, when I see lambdas used for this, it looks like:
>
> lambda *args, **kw: myfunc(partial_arg, *args, **kw)
Wrapper functions like that are almost always more readable when
written as named functions:
def my_modified_func(*args, **kwds):
return myfunc(partial_arg, *args, **kwds)
> which isn't more readable than just:
>
> partial(myfunc, partial_func)
It's significantly less clear that it's defining a new callable
though, especially for folks that have never heard the phrase "higher
order function".
It sometimes the right answer in particular contexts (hence the
availability of functools.partial), but it does immediately raise an
additional barrier to entry for future mainteners of that code (not a
particularly *high* barrier as these things go, but a barrier
nonetheless).
> Doing something like:
>
> lambda x, y: myfunc(partial_arg, x, y)
>
> is more error-prone to changes in myfunc's signature.
This form of lambda usage is more commonly seen when the lambda is
being used to adapt to a particular callback protocol that passes a
certain number of positional arguments to the callbacks (think things
like "key" arguments to sorting functions, error handlers, event
handlers, etc)
In those cases, having the lambda definition right there may help the
*reader* remember (or learn!) the callback signature. Consider:
mylist = sorted(original, key=(lambda item: measure(item, setting=2))
Even if this is the first time you've seen sorted(), and you've never
seen measure(), you know immediately the key function takes one
parameter, and can probably make a decent guess as to how to change
the behaviour of that sorting operation.
By contrast:
mylist = sorted(original, key=partial(measure, setting=2))
doesn't give you any hint about the signature of the key parameter
unless you already know the signature of measure().
While many folks will already recognise the sorted/key combination
specifically, the same can't be said for callback parameters in
general.
Making as few prior assumptions as we can about the reader's prior
knowledge without making the code overly verbose is one of the core
aspects of enabling correct local reasoning about code, and enabling
folks to edit code correctly *without* global awareness of the code
base is one of the core skills in learning to write maintainable code
:)
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list