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

Michael Selik michael.selik at gmail.com
Wed Apr 6 13:36:40 EDT 2016


> On Apr 6, 2016, at 2:07 PM, ast <nomail at com.invalid> wrote:
> 
> 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 ?
> 
> def to_base(nber, base=16, use_af=True, sep=''):
>   assert isinstance(nber, int) and nber >= 0

> Without, python interpreter may crash later in the function
> or worse provide a meaningless result.

Crashing later isn the function is a *good* thing in many cases, because it provides a more specific error. Not only what input was bad, but *why* it was bad. [0]

Meaningless results might be meaningless to you, but your users may have thought of new ways to use your code. Assume they've thought of things you haven't.

You don't want to lock people into only your prescribed usage. Remember, they might have monkey-patched your dependency to do something really cool. Don't ruin their day with "discipline".

However, you might want to protect them from a subtle infinite loop or other traps that are tough to recover from. If it's an obvious infinity, well, that's their own fault. For example, ``range`` stops you from a zero step-size, but won't stop you from ``range(int(1e200))``.


More information about the Python-list mailing list