PEP new assert idiom
Raymond Hettinger
vze4rx4y at verizon.net
Sun Nov 7 01:35:23 EST 2004
"Paul Rubin" <http://phr.cx@NOSPAM.invalid> wrote in message
news:7xr7n62t0v.fsf at ruckus.brouhaha.com...
> Some time ago I found myself proposing a new "Validate" statement,
> which would work exactly like "assert", except:
>
> 1) it would throw a ValidationError instead of AssertionError
> if the condition failed
>
> 2) it would NOT be turned into a no-op by the optimizing compiler.
>
> The purpose is runtime validation of user data, rather than sanity
> checking the program logic. Example: I keep finding myself writing
> code like:
>
> x = float(raw_input('Enter a positive number: '))
> assert x > 0, 'number wasn't positive'
>
> This is incorrect because the assert statement is not guaranteed to be
> executed. I propose to say instead,
>
> validate x > 0, 'number wasn't positive'
>
> which would do the right thing.
Why do you need a statement for this?
IMO, a plain function will do the trick:
def validate(expression, msg=None):
if expression: return
if msg is None:
raise ValidationError
else
raise ValidationError(msg)
Raymond Hettinger
More information about the Python-list
mailing list