Entry
How can I make my assertions smarter?
Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 265, Magnus L. Hetland
"""
Packages: miscellaneous
"""
"""
> I'm using some simple functions to implement crude precondition,
> postcondition and invariant checking in Python classes.
>
> (Tim: please be gentle ;-)
>
> Is there some neat way to wrap these tests up so I can print any
> code expression that fails, e.g:
>
> Precondition failed foo.py line 42: spoon.shape == 'bent'
>
> which would appear at line 42 of foo.py as
>
> pre(spoon.shape == 'bent')
How about using (assuming that you won't use assert):
pre("spoon.shape == 'bent'")
And then using eval() in your code? Like...
"""
def pre(condition):
if not eval(condition):
raise "Precondition Failure", condition
"""
Pretty simple, IMO...
"""