[Python-ideas] Treat underscores specially in argument lists

Steven D'Aprano steve at pearwood.info
Tue Feb 17 13:10:47 CET 2015


On Mon, Feb 16, 2015 at 08:24:52PM -0800, Andrew Barnert wrote:
> On Feb 16, 2015, at 18:45, Ryan Gonzalez <rymg19 at gmail.com> wrote:
> 
> > It's usually in callbacks where you only care about a few arguments.
> 
> A perfect example is using Tk variable tracing in tkinter (for 
> validation or post-change triggering on widgets). The signature of the 
> trace callback is callback(name, index, mode). You almost never need 
> the index, you rarely need the mode, so you write:
> 
>     def callback(self, name, _, mode):

> In fact, you usually don't need the mode either (in fact, you often 
> don't even need the name), but you can't write this:
> 
>    def callback(self, name, _, _):
> 
> So instead you usually write something like:
> 
>    def callback(self, name, *_):

Do I? I'm pretty sure I don't. I'm too worried about future maintainers, 
who will probably be violent psychopaths who know where I live.

If the callback has signature name, index, mode, I write name, index, 
mode, and make it clear that the callback function is expected to 
receive exactly three arguments, and what they are.

That way, I don't have to care whether the caller passes those arguments 
by position or name. I don't have to change the signature of my callback 
if I decide in the future that I actually do want to use the index and 
the mode. If I look at the arguments in a debugger, I'll see sensible 
names for all three parameters. If I use some sort of extended traceback 
(e.g. the cgitb module), I'll see exactly what the parameters were. And 
if something goes wrong, I won't have to worry about future maintainers 
tracking me back to my home.



-- 
Steve


More information about the Python-ideas mailing list