Typing arguments in python

A. Lloyd Flanagan alloydflanagan at attbi.com
Wed Apr 16 23:30:11 CEST 2003


Dale Strickland-Clark <dale at riverhall.NOTHANKS.co.uk> wrote in message news:<e9oq9vc2lfmb50ga5aipr0unembkhfd9da at 4ax.com>...
> danra at walla.co.il (Danra) wrote:
> 
> >def f(fileobj):
> >    if not hasattr(fileobj,'write'):
> >        raise TypeError, "Given arg must have the 'write' attribute."
> >    .
> >    .
> >    fileobj.write('...')
> 
> You want assert, you do:
> 
> def f(fileobj):
>     assert hasattr(fileobj, 'write'), 'Bang! Sort your code out.'

Actually, I'm going to disagree.  Some people don't recommend using
assert for checking parameters, for a couple of reasons.  First, it's
probably a good idea to continue to check parameters of your functions
even in production use.  That's really a pretty basic defensive
programming practice.

The second reason is more subtle.  An assert is technically a
statement that a certain condition can't happen under any
circumstances.  It's used to verify that the code in the function has
the expected effect on the state of the program.  But being called
with an incorrect parameter is NOT a flaw in the code that contains
the assert -- it's a problem with the caller.  Basically, instead of
saying, "hey, buddy, that parameter is wrong" you're now saying
"whoops, there's a bug in my code somewhere".  For a bad parameter you
should raise ValueError or something similar, not AssertionError.

Just my two cents as usual...




More information about the Python-list mailing list