[Python-ideas] Raise exception if (not) true
Andrew Barnert
abarnert at yahoo.com
Thu Feb 20 19:18:24 CET 2014
On Feb 20, 2014, at 9:29, MRAB <python at mrabarnett.plus.com> wrote:
> 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! :-)
And if you really want it in your project, it's a trivial one-liner, so just write it and use it.
More information about the Python-ideas
mailing list