How to validate the __init__ parameters

Lie Ryan lie.1296 at gmail.com
Tue Dec 22 10:10:22 EST 2009


On 12/22/2009 8:52 PM, Bruno Desthuilliers wrote:
> 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.

Let me give a more concrete example I've just stumbled upon recently:

This is a Tkinter Text widget's insert signature:

insert(self, index, chars, *args)
     Insert CHARS before the characters at INDEX. An additional
     tag can be given in ARGS. Additional CHARS and tags can follow in ARGS.

Let's simplify the signature to focus on one particular case (inserting 
just one pair of text and tag):

insert(self, index, chars, tags)

I want to write a wrapper/subclass Tkinter Text widget, then I read 
something that essentially means: tags must be a tuple-of-strings, 
cannot be a list-of-strings, and if you pass string "hello" it is 
interpreted as ('h', 'e', 'l', 'l', 'o') tags.

This is a bug-prone signature, I could have written (and indeed just 
minutes *after* reading the warning, though I caught it before any real 
harm was done, I wrote):

   insert(INSERT, chars="some text", tags="the_tag")

since I was intending to subclass Text anyway; I decided to throw an 
"assert isinstance(tags, tuple)" here rather than risking a bug caused 
by mindlessly using string. The only time the assert would fail is when 
I'm writing a bug, and there is no reason *I* would want a 
character-wise tag and write them as string instead of tuple of chars.

It could have been more subtle, I might have written
   insert(INSERT, chars="some text", tags="b")
and the code worked flawlessly, until I decided to copy'n'paste it to:
   insert(INSERT, chars="some text", tags="em")
and wondered why I can't find the "em" tag.



More information about the Python-list mailing list