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

Steven D'Aprano steve+python at pearwood.info
Tue Aug 9 21:29:28 EDT 2016


On Wed, 10 Aug 2016 06:51 am, Juan Pablo Romero Méndez wrote:

> 2016-08-09 13:18 GMT-07:00 Rob Gaddi <rgaddi at highlandtechnology.invalid>:

>> 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. We expect them to read the docs, which will say something like "expects
a list". Anything that behaves like a list *should* do: if something
behaves like a list, then it might as well be a list, regardless of whether
or not it inherits from the list built-in type or not. This is called Duck
Typing:

"If it quacks like a duck, swims like a duck and walks like a duck, it might
as well be a duck."

If your function wants an object it can call extend on, then why should it
demand a list? It should only care about whether or not the object has an
extend method.

Some functions may be stricter, either from some specific need, or just
because the author is a refugee from a statically typed language who thinks
that they need to type-check *everything*. (May the gods preserve us from
such people.)

In that case, your testing will quickly reveal that a list-like object is
not good enough, only an actual list will do.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list