On Jan 25, 11:54 am, Matthew Wilson <[EMAIL PROTECTED]> wrote: > Lately, I've been writing functions like this: > > def f(a, b): > > assert a in [1, 2, 3] > assert b in [4, 5, 6] > > The point is that I'm checking the type and the values of the > parameters. > > I'm curious how this does or doesn't fit into python's duck-typing > philosophy. > > I find that when I detect invalid parameters overtly, I spend less time > debugging. > > Are other people doing things like this? Any related commentary is > welcome. > > Matt
Well, duck (or even static for that matter) typing can't help you if you're checking for specific *values*, not types. The real question is rather, is f() intended to be used in the "outside world" (whatever this might be; another program, library, web service, etc.) or is it to be called only by you in a very controlled fashion ? In the first case, passing an invalid input is a *user error*, not a *programming error*. Assertions should be used for programming errors only to assert invariants, statements which should be correct no matter what; their violations mean that the code is buggy and should be fixed asap. User errors OTOH should be handled by explicit checking and raising appropriate exceptions, e.g. ValueError or a subclass of it. There are several reasons for this but a very practical one is that a user can turn off the assertions by running python with '-O' or '-OO'. Optimization flags should never change the behavior of a program, so using assertions for what's part of the normal program behavior (validating user-provided input) is wrong. George -- http://mail.python.org/mailman/listinfo/python-list