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

Chris Angelico rosuav at gmail.com
Wed Apr 6 09:27:06 EDT 2016


On Wed, Apr 6, 2016 at 11:07 PM, ast <nomail at com.invalid> wrote:
> 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
>
>   tbc
>
> 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 ?

Most likely, it'll raise an exception at some point - or, even more
likely, function *correctly*. For instance, why should your sep have
to be a one-character string? Most likely, you'll simply append it
periodically, or use sep.join(parts) to assemble everything; a
multi-character string should be fine. I don't know what "use_af"
means, but again, you're probably going to simply use it in a boolean
context (most basically, that would mean "if use_af: do_stuff"), so
truthiness/falsiness will do.

So, what I'd do is: Drop the assertions. If you actually need the
checks, DO NOT use assert, but actually check and raise something else
(maybe ValueError). 'assert' should NEVER be used to check external
input.

ChrisA



More information about the Python-list mailing list