Reverse argument order

Paul Winkler slinkp23 at yahoo.com
Sat Oct 20 19:16:54 EDT 2001


On Sat, 20 Oct 2001 21:53:52 GMT, Bengt Richter <bokr at accessone.com> wrote:
>Brute force, but clear:
>
> >>> def wait(first=None,second=None,third=None):
> ...     if third: h,m,s = first,second,third
> ...     elif second: h,m,s=0,first,second
> ...     elif first: h,m,s=0,0,first
> ...     else: h,m,s=0,0,0
> ...     print "h=%d, m=%d, s=%d" % (h,m,s) # or whatever you want to do
> ...
> >>> wait()
> h=0, m=0, s=0
> >>> wait(1)
> h=0, m=0, s=1
> >>> wait(1,2)
> h=0, m=1, s=2
> >>> wait(1,2,3)
> h=1, m=2, s=3

This is broken!

>>> wait(1,2,3)
h=1, m=2, s=3
>>> wait(1,0,0)
h=0, m=0, s=1

Clearly the user intended to get h=1, m=0, s=0.

Fix: Change it so your tests look like "if third is not None:"
... etc.  Then it works:

>>> wait(1,0)
h=0, m=1, s=0
>>> wait(1,0,0)
h=1, m=0, s=0
>>> wait(1,0,5)
h=1, m=0, s=5

But it's still not great, because the function def implies that this
function can take keyword args when in fact it can't:

>>> wait(second=9)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in wait
TypeError: an integer is required

That could confuse a user who actually bothered to learn python.

I think Kirill's solution (among others) is better; it does the right
thing with inappropriate keyword args:

TypeError: wait() got an unexpected keyword argument 'foo'


--Paul Winkler





More information about the Python-list mailing list