[Python-ideas] Raise exception if (not) true
Ryan Gonzalez
rymg19 at gmail.com
Thu Feb 20 18:10:58 CET 2014
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?
--
Ryan
If anybody ever asks me why I prefer C++ to C, my answer will be simple:
"It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was
nul-terminated."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140220/07ec856c/attachment-0001.html>
More information about the Python-ideas
mailing list