[Python-ideas] Raise exception if (not) true

spir denis.spir at gmail.com
Thu Feb 20 21:44:57 CET 2014


On 02/20/2014 06:29 PM, MRAB 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!')
>
> ?

And:
     raise_if(x!=y, ValueError, 'x != y!!')
is equivalent to:
     if x != y: raise ValueError('x != y!!')

> It doesn't improve the language much, IMHO! :-)

Ditto.

But I would like to be able to add an error type to assertions (in addition to 
the optional message). This is particularly useful for people (like me) who 
systematically check func inputs (for client debugging comfort), using assert's. 
It would be mainly ValueError and TypeError.

Example:
     assert x > 0, "x should be positive", ValueError
gives:
     ValueError: x should be positive
instead of:
     AssertionError: x should be positive

This is very similar to the proposal above, semantically and practically, except 
we are here just reusing the builtin 'assert' instruction with an additional 
parameter. (Seems backward-compatible to me, at first sight, provided the new 
param comes last. Maybe an issue is the hypothetical mention of an error type, 
without message.)

d


More information about the Python-ideas mailing list