list(), tuple() should not place at "Built-in functions" in documentation

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 16 00:06:21 EDT 2011


Inside wrote:

> Why I use assertion,please check this code:
> """
> class User(object):pass
> 
> class Student(User):pass
> 
> class Professional(User):pass
> 
> def add(user):
>     assert(user, User)

This does not do what you think it does. All it does is, in some Python
versions, print 

SyntaxWarning: assertion is always true, perhaps remove parentheses?

In other Python versions, it is a no-op: it does nothing.

Perhaps you meant this?

assert isinstance(user, User)

Ben has already posted why isinstance type-checking should usually be
avoided in favour of duck-typing ("if it looks like a duck, and sounds like
a duck, and swims like a duck, it might as well be a duck"). But let's
suppose you have good reason for sticking to an explicit type-check. The
problem now is with the assert! Assertions are not guaranteed to run. The
caller can turn them off by running Python with the -O (optimize) switch.

Another problem: AssertionError is the wrong sort of exception to raise on
bad arguments. It should normally be TypeError or ValueError, or some other
more specific exception, with a useful error message.

Assertions are for testing your own program logic, not for validating input.
For example, in one of my own libraries, I have this piece of code:

data = _countiter(data)
assert data.count == 0
total = sum(data)
n = data.count
assert n >= 0
# much later on...
return math.sqrt(value/n)


_countiter is a wrapper that keeps track of how many items have been
iterated over. I take an arbitrary iterator, wrap it, sum the values, then
check that the number of items is not a negative number. If it is, that's a
bug in my program logic, and I should find out as soon as possible, not
much later on when I try to take the square root of it.

Assertions should be rare, and never used for testing arguments (except,
maybe, for purely internal functions that only get called by your own
functions, never by the caller). If the caller ever sees an AssertionError
generated by your code, that is a bug in your code.



-- 
Steven




More information about the Python-list mailing list