On Thursday 18 March 2010, Colin Morris wrote:

> > Please don't warn on literal False, since I use that quite often in
> > situations like this:
> > 
> >        if a.hasSomeProperty():
> >                doSomething()
> >        elif a.hasSomeOtherProperty():
> >                doSomethingElse()
> >        else:
> >                assert False, 'a is in an invalid state'
> 
> Wouldn't "raise AssertionError('a is in an invalid state')" be more
> clear?

It is not equivalent: asserts are removed when byte-compiling in optimized 
mode (.pyo instead of .pyc). Also, I think "assert False" is easier to read.

> Or "raise ValueError('a is an invalid state')"?

Raising ValueError is the right thing to do if the caller passes an object 
in an invalid state. If there is an internal inconsistency, asserts are 
better.

> Or, if you
> wanted to use an assert, why not put it before the if block and do
> "assert a.hasSomeProperty() or a.hasSomeOtherProperty(), 'a is an
> invalid state'"?

That is possible, but then the code looks like this:

        if a.hasSomeProperty():
                doSomething()
        else:
                assert a.hasSomeOtherProperty(), 'a is in an invalid state'
                doSomethingElse()

In my opinion this is less readable since it does not follow the same 
pattern for each case like the original example does. This becomes more 
pronounced if there are more cases.

Also, if all cases are disjunct, the order of the checks does not matter for 
correctness. For performance it is then best to place the case that is most 
likely true first. This kind of refactoring is less effort if it is just a 
matter of moving the corresponding "elif" and its block to a different 
place.

Finally, it is not equivalent since it will do something different when 
assertions are disabled. However, unless you are very consciously doing 
defensive programming, it doesn't really matter what a program in an 
inconsistent state does, since it is not easy to tell which alternative is 
better.

> I'm not a Python guru, but those seem more idiomatic
> to me. Still, I agree that asserting a tautology seems somehow 'worse'
> than asserting a contradiction, since the latter actually has some
> effect.

Unlike the "assert (a, b)" case, it's very unlikely that "assert False" is 
written accidentally when the programmer meant something else. So warning 
about it is unlikely to make anyone happy, while it would make me unhappy.

Bye,
                Maarten
_______________________________________________
Python-Projects mailing list
[email protected]
http://lists.logilab.org/mailman/listinfo/python-projects

Reply via email to