How to validate the __init__ parameters

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Dec 22 04:52:18 EST 2009


Steve Holden a écrit :
(snip)
> What's the exact reason for requiring that a creator argument be of a
> specific type? So operations on the instances don't go wrong? Well, why
> not just admit that we don't have control over everything, and just *let
> things go wrong* when the wrong type is passed?

validation isn't only about types, but that's not the point...

> What will then happen? Why, an exception will be raised!

Not necessarily.

def nocheck(stuffs):
    "'stuffs' is supposed to be a sequence of strings"
    for s in stuffs:
       do_something_with(s)


# correct call
good_stuffs = ("role1", "role2", "role3")
nocheck(good_stuffs)

# incorrect call, but the error passes silently
bad_stuffs = "role1"
nocheck(bad_stuffs)


If nocheck happens to be in the core of a huge lib or framework and 
stuffs defined somwhere in a huge client app's code you didn't even 
wrote, then you might spend hours tracing the bug - been here, done 
that, bought the tshirt :(

IOW : while I agree that not doing anything and letting exceptions 
propagate is quite often the best thing to do, there are times where 
validation makes sense - specially when passing in a wrong value might 
NOT raise an exception - just produce unexpected results.

My 2 cents...



More information about the Python-list mailing list