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


Groups > comp.lang.python > #106574

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

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: Checking function's parameters (type, value) or not ?
Date 2016-04-06 23:27 +1000
Message-ID <mailman.130.1459949229.32530.python-list@python.org> (permalink)
References <57050a05$0$4546$426a34cc@news.free.fr> <CAPTjJmqXP9QNC97WKX41FsNze_8vHcBY626VG+A6rE3fOQ640g@mail.gmail.com>

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

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

csiph-web