[Python-ideas] Short form for keyword arguments and dicts

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Jun 26 00:09:42 CEST 2013


Andrew Barnert wrote:

> I've already asked Anders this, but let me ask you as well: 
 > What are the use cases you have in mind?
> 
> As I see it, there are three cases ...
> 1. dict constructor
> 2. str.format
> 3. forwarding functions (like my example with get_appdir_url)

Mine are all 3. Here's a simplified version of something
that crops up in various places in my GUI libraries. I have
a widget, let's say a Button, and I want to calculate a
default size for it during construction. To do that I need
to know its font, which is one of the things that can
potentially be passed as an argument to the constructor.
So I want to "peek" at the font argument as it goes by:

     class Button(Widget):

         def __init__(self, text = "Hello", font = system_font, **kwds):
             default_size = calc_default_size(text, font)
             Widget.__init__(self, size = default_size, font = font, **kwds)

(I should also point out that my Widget constructor accepts
a very large set of potential keyword arguments (essentially
any of its assignable properties) so passing them positionally
is not an option.)

Now, it's not so bad when there are only one or two passed-on
arguments, but if you have a handful it starts to feel a bit
wanky.

I think I've figured out why this seemingly-small amount of
redundancy bothers me so much. It's not just that I feel I'm
saying the same thing twice, but that I feel I'm not saying
*anything at all*. If I were to write this as an ordinary
assignment:

    font = font

then it would be completely redundant. Now I know full well
that it's different with a keyword argument, because the two
sides live in different namespaces. But some part of my brain
still tries to tell me that I'm doing something silly -- to
the extent that sometimes I'm tempted to deliberately give the
two sides *different* names just so that it doesn't look so
useless.

> And, if it is just #3, do you have the same argument that (I think) Anders has,
> or a different one?

A different one. I'm not on any kind of crusade to push the
use of keyword arguments for everything.

-- 
Greg


More information about the Python-ideas mailing list