Type checking versus polymorphism (was: list(), tuple() should not place at "Built-in functions" in documentation)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 16 08:33:12 CEST 2011

Chris Rebert wrote:

> On Fri, Jul 15, 2011 at 7:47 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
> <snip>
>> Assertions are for testing internal program logic, not for validation.
>> (I don't even like using assert for testing. How do you test your code
>> with assertions turned off if you use assert for testing?)
> I would think that would only matter if either the asserted
> expressions caused side-effects or there was nontrivial logic in the
> AssertionError handler, which would indicate a rather screwy codebase 
> and point to a possible PEBKAC issue that testing cannot hope to
> remedy.

I'm not sure I follow you there... 

For any piece of code, I claim that we should test both with and without
the -O switch. If I don't test it with -O, how do I know it works correctly
when run with -O? Even if I don't use assert yourself, I don't know if the
code I call uses assert badly and therefore is affected by -O.

(I recently discovered that ElementTree, in the Python standard library,
uses assert for data validation in at least some Python versions.)

Besides, I don't know what -O does, apart from disabling assertions. Maybe
nothing else. Maybe lots of things. It may change from version to version.
Who knows? Whatever it does, it *shouldn't* change the semantics of my
code, but it *could*, hence I better test it to find out if anything has

So are we agreed that it is wise to test code both with and without the -O

But here's the problem... the -O switch is global, and not module specific.
So if your test suite looks like this:

import mymodule
assert hasattr(mymodule, "__all__")
assert isinstance(mymodule.__version__, str)
assert mymodule.count_spam("spam spam spam") == 3
a, b, c = mymodule.aardvark(42)
assert a < b < c

when running with -0, all those tests LITERALLY go away and you're left with
a significantly smaller test suite:

import mymodule
a, b, c = mymodule.aardvark(42)

which is hardly better than no test at all.


More information about the Python-list mailing list