using builtin exceptions

Alex Martelli aleax at aleax.it
Mon Mar 3 10:26:43 CET 2003


Erik Price wrote:

> Is it considered bad practice to appropriate the "builtin" exceptions
> that ship with the stdlib in our own programs?  For instance,
> "ValueError" is explicitly described by the documentation as being for
> the use of builtin functions only ("Raised when a built-in operation or
> function receives an argument that has the right type but an
> inappropriate value, and the situation is not described by a more
> precise exception such as IndexError."), but it's the exact same

I think you may be reading the docs in a different and stricter
way from how they were meant.  There is no "only" in the text you
quote from the docs -- that's in your interpretation.  And I do
not think "Y happens when X" should be interpreted as "Y happens
ONLY when X, and you're forbidden from ever making Y happen in
any other case [even though the current interpreter does not yet
enforce this prohibition]".  Explicit is better than implicit: if
the docs meant such a thing, they should express it explicitly.

> purpose I have in mind if I use it in my code:
> 
> ###
>      def __init__(self, shift_type, shift_start, shift_stop):
>          if not Shift.pay_rates.has_key(shift_type):
>              raise KeyError
>          if shift_start > shift_stop:
>              raise ValueError
>          ...
> ###
> 
> So is this okay to do?  I ask this not strictly from a pragmatic
> perspective but also from a stylistic one....

I think it's OK regarding the issue in Subject:.  It's probably
suitable for enhancements on other scores -- e.g. if this is the
__init__ for class Shift, or a subclass thereof which does not
override the class attribute named pay_rates, then I think the
reference should be to self.pay_rates, NOT to Shift.pay_rates,
to allow future subclasses to perform "data overriding" on that
attribute (as discussed in a recent thread about Borg vs
Singleton).  But I don't think this is what you're asking about...


Alex





More information about the Python-list mailing list