Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #106571 > unrolled thread

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

Started by"ast" <nomail@com.invalid>
First post2016-04-06 15:07 +0200
Last post2016-04-07 02:30 +1000
Articles 6 — 4 participants

Back to article view | Back to comp.lang.python


Contents

  Checking function's parameters (type, value) or not ? "ast" <nomail@com.invalid> - 2016-04-06 15:07 +0200
    Re: Checking function's parameters (type, value) or not ? Chris Angelico <rosuav@gmail.com> - 2016-04-06 23:27 +1000
    Re: Checking function's parameters (type, value) or not ? Mark Lawrence <breamoreboy@yahoo.co.uk> - 2016-04-06 14:29 +0100
      Re: Checking function's parameters (type, value) or not ? "ast" <nomail@com.invalid> - 2016-04-06 16:18 +0200
        Re: Checking function's parameters (type, value) or not ? "ast" <nomail@com.invalid> - 2016-04-06 19:49 +0200
    Re: Checking function's parameters (type, value) or not ? Steven D'Aprano <steve@pearwood.info> - 2016-04-07 02:30 +1000

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

From"ast" <nomail@com.invalid>
Date2016-04-06 15:07 +0200
SubjectChecking function's parameters (type, value) or not ?
Message-ID<57050a05$0$4546$426a34cc@news.free.fr>
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 ?

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

   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 ?
    
 

[toc] | [next] | [standalone]


#106574

FromChris Angelico <rosuav@gmail.com>
Date2016-04-06 23:27 +1000
Message-ID<mailman.130.1459949229.32530.python-list@python.org>
In reply to#106571
On Wed, Apr 6, 2016 at 11:07 PM, ast <nomail@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

[toc] | [prev] | [next] | [standalone]


#106575

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2016-04-06 14:29 +0100
Message-ID<mailman.131.1459949361.32530.python-list@python.org>
In reply to#106571
On 06/04/2016 14:07, 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 ?
>
> 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
>
>    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 ?
>


Please see 
http://ftp.dev411.com/t/python/python-list/13bhcknhan/when-to-use-assert

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

[toc] | [prev] | [next] | [standalone]


#106582

From"ast" <nomail@com.invalid>
Date2016-04-06 16:18 +0200
Message-ID<57051aa7$0$19735$426a34cc@news.free.fr>
In reply to#106575
"Mark Lawrence" <breamoreboy@yahoo.co.uk> a écrit dans le message de 
news:mailman.131.1459949361.32530.python-list@python.org...
> On 06/04/2016 14:07, ast wrote:

>
> Please see http://ftp.dev411.com/t/python/python-list/13bhcknhan/when-to-use-assert
>


Thanks for this paper

Running Python with the -O or -OO optimization flags
removes the assert. This has to be known. 

[toc] | [prev] | [next] | [standalone]


#106591

From"ast" <nomail@com.invalid>
Date2016-04-06 19:49 +0200
Message-ID<57054c31$0$19774$426a74cc@news.free.fr>
In reply to#106582
"Chris Angelico" <rosuav@gmail.com> a écrit dans le message de 
news:mailman.13.1459955565.1197.python-list@python.org...
On Thu, Apr 7, 2016 at 12:18 AM, ast <nomail@com.invalid> wrote:
> "Mark Lawrence" <breamoreboy@yahoo.co.uk> a écrit dans le message de
> news:mailman.131.1459949361.32530.python-list@python.org...
>>
>> On 06/04/2016 14:07, ast wrote:
>


>> Running Python with the -O or -OO optimization flags
>> removes the assert. This has to be known.
>
>Exactly. So your two options are not "remove the assertions" and "keep
>the assertions"; they are "remove the assertions" and "replace the
>assertions with explicit exception raising". My recommendation is
>still on simply removing them, but if you are to keep the checks,
>they'll look something like this:
>
>def to_base(nber, base=16, use_af=True, sep=''):
>    """docstring goes here (don't forget that)"""
>    nber = int(nber)
>    if nber < 0: raise ValueError("Negative numbers not supported")
>    base = int(base)
>    if base < 2: raise ValueError("base must be at least 2")
>    use_af = bool(use_af)
>    sep = str(sep)
>
>
>These are either conversions or assertions, depending on your point of
>view. Actually, it would be better for these to have some kind of
>"ensure that this is X" call; you could replace int(x) with
>operator.index(x), but there's no equivalent for str - any object can
>be converted to a string. You could perhaps do that one with
>isinstance. (IMO bool is fine as it is.)
>
>But I would just leave out this code altogether. Less code means less
>chance of bugs creeping in; you might change the code elsewhere to
>require, for instance, that base not exceed 36, and then you'd have to
>come and change this code too. Without the checks, you'd only make
>that change in one place.
>
>ChrisA

thanks for these informations 

[toc] | [prev] | [next] | [standalone]


#106588

FromSteven D'Aprano <steve@pearwood.info>
Date2016-04-07 02:30 +1000
Message-ID<570539a4$0$1598$c3e8da3$5496439d@news.astraweb.com>
In reply to#106571
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

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web