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

Michael Torrie torriem at gmail.com
Wed Aug 10 00:51:50 EDT 2016


On 08/09/2016 02:51 PM, 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?

There are type annotations you can use in Python 3 that can help
document the expected type that a function requires, and that
information can be used by a linter to predict problems.  Since Python
allows duck typing, one could say that my function requires a
"file-like" object.  Not sure how that would be annotated.

Some people go to more formal extremes and rather than just rely on duck
typing they will use Java-style formal interfaces.  So the function
could require an object that implements certain interfaces.
https://pypi.python.org/pypi/zope.interface. I suppose with interfaces,
the function could query the arguments to look for these interfaces. But
really in my mind that's no different than duck typing because if an
object comes in that you can't deal with, that's by definition and
exception anyway. So either Python raises it for you or you raise it
yourself after checking for an interface.  Same effect in my mind.





More information about the Python-list mailing list