What are some other way to rewrite this if block?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Mar 18 11:07:01 EDT 2013
On Mon, 18 Mar 2013 15:32:03 +0100, Jean-Michel Pichavant wrote:
> You can remove the 'if' line, report_status asks for hours, the caller
> is supposed to provide valid hours. What if the caller gives you
> strings, integer, floats ? This is a never ending story.
I see you haven't been a programmer very long *wink*
Yes, error checking and data validation is a never ending story. Welcome
to programming. That's what we do.
> def report_status(should_be_on, came_on):
>
> # well if you really really want to test it
> assert(all([int(arg) in range(0,24) for arg in
> (should_be_on, came_on)]))
Please don't use assert for argument checking in public APIs. (And
probably not in private APIs either.) assert is wrong for two reasons:
1) Invalid arguments should raise TypeError or ValueError. You wouldn't
arbitrarily raise KeyError("expected 0 < arg < 24 but got arg = -1") or
IOError("expected an int but got a string"). That would be unprofessional
and foolish. So why raise AssertionError?
2) assert is not guaranteed to run, and you have *no control over it*. If
the user calls python with the -O flag, asserts are disabled and your
error checking is never performed.
assert is designed to verify internal logic of your code, not caller-
facing argument validation.
--
Steven
More information about the Python-list
mailing list