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


Groups > comp.lang.python > #79408

Re: When to use assert

References <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com>
Date 2014-10-22 12:53 +1100
Subject Re: When to use assert
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.15053.1413942836.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Oct 22, 2014 at 12:44 PM, Steven D'Aprano
<steve+comp.lang.python@pearwood.info> wrote:
> def do_something(instance_or_id):
>     instance = Model.get(instance_or_id)
>     assert isinstance(instance, Model)
>     # Code that assumes that instance is an object of type Model
>
>
> That means that the logic for what is acceptable as a Model is all in one
> place, namely the Model.get method, and callers don't need to care about
> the pre-condition "argument is a Model or an integer ID", they only need to
> care about the post-condition "result of get() is a Model".

And at that point, the assertion is redundant, on par with:

a = len(seq)
assert isinstance(a, int)

because you shouldn't have to assert what's part of a function's guarantee.

ChrisA

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


Thread

Re: When to use assert Anton <anton.schattenfeld@gmail.com> - 2014-10-21 00:48 -0700
  Re: When to use assert Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-10-22 12:44 +1100
    Re: When to use assert Chris Angelico <rosuav@gmail.com> - 2014-10-22 12:53 +1100
      Re: When to use assert Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-10-23 02:49 +1100
        Re: When to use assert Chris Angelico <rosuav@gmail.com> - 2014-10-23 03:01 +1100
        Re: When to use assert Dan Stromberg <drsalists@gmail.com> - 2014-10-22 09:18 -0700
          Re: When to use assert Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-10-24 18:49 +1100
            Re: When to use assert Chris Angelico <rosuav@gmail.com> - 2014-10-24 19:18 +1100
              Re: When to use assert Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-10-26 20:39 +1100
                Re: When to use assert Chris Angelico <rosuav@gmail.com> - 2014-10-26 20:51 +1100

csiph-web