Optimize flag question

Felipe Almeida Lessa felipe.lessa at gmail.com
Sun Feb 26 04:45:02 EST 2006


Em Sáb, 2006-02-25 às 17:56 -0800, bonono at gmail.com escreveu:
> Steve Holden wrote:
> > > 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.
> >
> What would be the occasion that AssertionError be the right exception
> to raise then ?

IMHO, assertions should be used in places where things are obvious. For
example, you can check if a object is of a given type to avoid using it
on a bad context. *But*, those checks are just to help you while coding,
not at runtime. If you want those checks at runtime, you should be using
if's.

Using other words, assertions should be used only when you know a priori
that the assertion should *never* fail in a production system.

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"




More information about the Python-list mailing list