Checking function's parameters (type, value) or not ?

Steven D'Aprano steve at pearwood.info
Wed Apr 6 12:30:27 EDT 2016


On Wed, 6 Apr 2016 11:07 pm, ast wrote:

> Hello
> 
> I would like to know if it is advised or not to test
> a function's parameters before running it, e.g
> for functions stored on a public library ?

It depends. Sometimes it is best to do an explicit type check, sometimes it
is better to call a built-in function that will do the type checking for
you, and sometimes it is best to use "duck typing":

https://en.wikipedia.org/wiki/Duck_typing


> Example:
> 
> def to_base(nber, base=16, use_af=True, sep=''):
> 
>     assert isinstance(nber, int) and nber >= 0
>     assert isinstance(base, int) and base >= 2
>     assert isinstance(use_af, bool)
>     assert isinstance(sep, str) and len(sep) == 1

Do not use assert for checking arguments, that is completely wrong and
dangerous, as the user can disable your error checking.

Please read this article about assert:

https://import-that.dreamwidth.org/676.html


> With these tests, you are sure that the function to_base is
> well used. But it slows down the program.
> Without, python interpreter may crash later in the function
> or worse provide a meaningless result.
> 
> What library designers do ?


Why don't you read the source code to the Python standard library? You will
learn what library designers do.

If you have Python installed, you will have the source code. Or you can read
it here:

https://hg.python.org/cpython/file/3.5/Lib/


I'm especially fond of this one, since I wrote it:

https://hg.python.org/cpython/file/3.5/Lib/statistics.py

You will notice that there are very few explicit type-checks, but if you
look at the unit-tests, there are tests to ensure that the functions raise
the correct TypeError as needed:

https://hg.python.org/cpython/file/3.5/Lib/test/test_statistics.py

(Search for test_bad_arg_types and test_strings_fail, for example.)



-- 
Steven




More information about the Python-list mailing list