Optimize flag question

Steve Holden steve at holdenweb.com
Sat Feb 25 16:32:07 EST 2006


[copied to python-list]

Olivier Langlois wrote:
> Hi Steve!
> 
>>Could you outline the code that needs to be in to make the program
> 
> work,
> 
>>so we can assess the errors for ourselves?
>>
> 
> 
> There is nothing unfixable. There are some instances where the code is
> checking a function return value like:
> 
> assert(Somefunc())
> 
> which could fix with
> 
> res = Somefunc()
> assert(res)
> 
So what you are saying is that Somefunc() needs to be executed, 
presumably because it has side-effects?

Yes, it would be much better to recast it, but ...

> Some other functions rely on the AssertionError exception to indicate to
> the user that something went wrong instead of using a user defined
> exception.
> 

The real problem here is that you appear to be using AssertionError in 
an inappropriate way. If some caller passes an incorrect argument to 
your function, raise a ValueError. If you are passed the wrong type of 
data, raise a TypeError. And so on. Or, as you imply you thought about, 
raise a user-defined error.

Generally speaking you should reserve assert for circumstances where you 
expect some invariant condition to be true. Otherwise use an "if" 
statement and raise some other exception if the condition is True.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list