When to use assert

Chris Angelico rosuav at gmail.com
Tue Oct 21 21:53:46 EDT 2014


On Wed, Oct 22, 2014 at 12:44 PM, Steven D'Aprano
<steve+comp.lang.python at 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



More information about the Python-list mailing list