What's the best way to minimize the need of run time checks?

Rob Gaddi rgaddi at highlandtechnology.invalid
Tue Aug 9 17:02:05 EDT 2016


Juan Pablo Romero Méndez wrote:

> 2016-08-09 13:18 GMT-07:00 Rob Gaddi <rgaddi at highlandtechnology.invalid>:
>
>> Juan Pablo Romero Méndez wrote:
>>
>> > 2016-08-09 12:06 GMT-07:00 Paul Rubin <no.email at nospam.invalid>:
>> >
>> >> Juan Pablo Romero Méndez <jpablo.romero at gmail.com> writes:
>> >> > In online forums sometimes people complain that they end up having to
>> >> > test constantly for None
>> >>
>> >> That's something of a style issue.  You can code in a way that avoids a
>> >> lot of those tests (not all of them).
>> >>
>> >
>> >
>> > This is exactly what I'm looking for :).  Do you have any resource (blog
>> /
>> > book, etc) that discusses this style?
>> >
>>
>> It's not a style, it's the absence of one.
>>
>> def add2list(lst, elem):
>>     lst.extend([elem, elem])
>>     return lst
>>
>> I did all the type checking I needed to there; none whatsoever.  If
>> passed a list, or something that behaves like one, that does the
>> expected thing.
>>
>> If passed an ExtensionLadder, it probably does the wrong thing, but that
>> is no way my problem.
>>
>
>
> So as the writer of the function you expect the user to read the function
> body to determine what is safe to pass or not?
>

No, but I expect them to read the function documentation.  The
alternative is to expect that the user is going to go around trying to
randomly call functions with whatever objects they happen to have lying
around in an attempt to figure out what they do.  The docstring for the
above function would probably be """Append two copies of elem to the
end of list lst."""

This goes back to the "consenting adults" principle in Python. 
Assume that the person calling your functions isn't a blithering moron
in need of protection from themselves. Sometimes you'll be wrong in
that assumption, but their life as a blithering moron is already quite
difficult and so you won't have substantially added to that by failing
to put guard rails up on your function. Conversely, if you explicitly
check isinstance(lst, list) then I can't, as one clever SOB, pass
it a list-like object and have it just work.  I instead would have to
have my object expressly subclass list, even if I had a reason not to.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list