assertions to validate function parameters

Carl Banks pavlovevidence at gmail.com
Sat Jan 27 15:58:04 CET 2007



On Jan 25, 11:54 am, Matthew Wilson <m... at tplus1.com> 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.

The duck-typing thing fits into a wider philosophy of being liberal in 
what you accept.  As you're constraining what a function accepts, it 
definitely goes against the philosophy.  I suggest you not blindly 
slap assertions on every single function.

Assertions should only be used to check for ostensibly impossible 
conditions.  Therefore, guarding arguments like this is probably only 
a good idea for internal or private functions that you can personally 
guarantee will only be called with the right values.

Personally, I find assertions are more helpful in complex situtations 
where I find myself having to maintain some sort of invariant.  Some 
condition is supposed to always be true at this point, and my code 
relies on this.  I've taken steps to maintain the invariant, but I 
could have made a mistake.  So I throw an assertion in.  If there's a 
leak somewhere, it will catch it.


> I find that when I detect invalid parameters overtly, I spend less time
> debugging.

If it helps go ahead an use them.  The world won't end if you use an 
assertion in a less than ideal situation.  And, after all, if someone 
doesn't like it they can shut them off.


> Are other people doing things like this?  Any related commentary is
> welcome.

Well,  there are examples of this usage of assert the standard 
library.  Some public functions (off hand I can think of the threading 
module) use assertions to check for invalid arguments, a use I highly 
disagree with.  The library shouldn't be making assertions on behalf 
of the users.  If an AssertionError is raised from the threading 
module, it should be because there is a bug in the threading module, 
not because the user passed it a bad value.

But, yes, it has been done.


Carl Banks




More information about the Python-list mailing list