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

Steven D'Aprano steve at pearwood.info
Thu Feb 20 22:16:54 CET 2014


On Thu, Feb 20, 2014 at 11:10:58AM -0600, 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.

Which is why asserts do not help at all. If somebody is using an 
assertion merely to save typing out 

    if cond: raise MoreAppropriateError(message)

then their code is poorly-written and probably broken.


> I propose a `raise_if` function. If the given condition is True, an
> exception is raised. So, the above examples would be shortened to:

Put this at the top of your module:

def raise_if(condition, exception, message):
    if condition:
        raise exception(message)


Not every three line function needs to be a built-in.


-- 
Steven


More information about the Python-ideas mailing list