raise None

Chris Angelico rosuav at gmail.com
Wed Dec 30 19:38:12 EST 2015


On Thu, Dec 31, 2015 at 11:09 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> I have a lot of functions that perform the same argument checking each time:
>
> def spam(a, b):
>     if condition(a) or condition(b): raise TypeError
>     if other_condition(a) or something_else(b): raise ValueError
>     if whatever(a): raise SomethingError
>     ...
>
> def eggs(a, b):
>     if condition(a) or condition(b): raise TypeError
>     if other_condition(a) or something_else(b): raise ValueError
>     if whatever(a): raise SomethingError
>     ...
>
>
> Since the code is repeated, I naturally pull it out into a function:
>
> def _validate(a, b):
>     if condition(a) or condition(b): raise TypeError
>     if other_condition(a) or something_else(b): raise ValueError
>     if whatever(a): raise SomethingError
>
> def spam(a, b):
>     _validate(a, b)
>     ...
>
> def eggs(a, b):
>     _validate(a, b)
>     ...
>
>
> But when the argument checking fails, the traceback shows the error
> occurring in _validate, not eggs or spam. (Naturally, since that is where
> the exception is raised.) That makes the traceback more confusing than it
> need be.

If the validation really is the same in all of them, then is it a
problem to see the validation function in the traceback? Its purpose
isn't simply "raise an exception", but "validate a specific set of
inputs". That sounds like a perfectly reasonable traceback line to me
(imagine if your validation function has a bug).

ChrisA



More information about the Python-list mailing list