A trick for handling mutable default argumentsOne of the neat things about programming in Python is finding out about clever little idioms that are obvious in retrospect. My latest find is a little trick for handling mutable function arguments. As I mentioned back when discussing the consequences of
At two lines, this is just verbose enough to grate lightly but
irritatingly on my nerves. Compressing the
This works because the result of Python's boolean operators is not True
or False, but the last expression evaluated. So ' But there's a subtle (and fortunately rare) gotcha with this, pointed
out by the if it is considered true bit. Namely, if we pass in an
explicit argument that's considered to be false, we wind up with
This is even safe against silent success if someone accidentally passes
in an explicit (There is surely a better name for the helper function than Appropriately, the Ian Bicking blog entry I found this in is called Reducing boilerplate code in __init__, although he is talking about something much higher level than this. Sidebar: another obvious
|
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |