[Python-ideas] Raise exception if (not) true
MRAB
python at mrabarnett.plus.com
Thu Feb 20 18:29:20 CET 2014
On 2014-02-20 17:10, Ryan Gonzalez wrote:
> In Python, you'll constantly see code like this:
>
> ```python
> if x != y:
> raise ValueError('x != y!!')
> ```
>
> or:
>
> ```python
> if not isinstance(x,SomeType):
> raise TypeError('x is not SomeType!')
> ```
>
> Assertion help a bit:
>
> ```python
> assert isinstance(x,SomeType), 'x is not SomeType!'
> ```
>
> Notice I said "a bit". If optimizations are on, they're disabled. In
> addition, the only type of error thrown is an AssertionError.
>
> I propose a `raise_if` function. If the given condition is True, an
> exception is raised. So, the above examples would be shortened to:
>
> ```python
>
> raise_if(x!=y, ValueError, 'x != y!!')
> raise_if(not isinstance(x,SomeType),TypeError, 'x is not SomeType!')
>
> ```
>
> There could also be a raise_if_not function that does the opposite:
>
> ```python
> raise_if_not(isinstance(x,SomeType), TypeError, 'x is not SomeType!')
> ```
>
> Thoughts?
>
So:
raise_if_not(isinstance(x, SomeType), TypeError, 'x is not SomeType!')
is equivalent to:
if not isinstance(x, SomeType): raise TypeError('x is not SomeType!')
?
It doesn't improve the language much, IMHO! :-)
More information about the Python-ideas
mailing list