I love assert

Chris Angelico rosuav at gmail.com
Wed Nov 12 17:43:22 EST 2014


On Thu, Nov 13, 2014 at 7:53 AM, Anton <anton.schattenfeld at gmail.com> wrote:
> I am not sure how and when you use assert, but something that stops me from using assert is that in many cases I would use them to
> 1) Check type of an incoming argument/returned value
> 2) Check value of an incoming argument/returned value
> But the issues I can see here is that assert throws AssertError, while there is a specialized error for each of the case: 1) TypeError 2) ValueError.
> Moreover for the 1) case it makes it impossible to dynamically substitute an object with another object that implements the same interface.

The fact that there's a better exception type that's obviously more
correct is a strong hint that you shouldn't use assert for these two
cases. And your "Moreover" concern is a strong hint that you shouldn't
be checking at all :)

If you need to check this sort of thing, an explicit "if condition:
raise SomeError('message')" construct is a lot more useful. Otherwise,
there's no reason to have the line of code at all.

ChrisA



More information about the Python-list mailing list