How can I make my assertions smarter?

Magnus L. Hetland mlh at vier.idi.ntnu.no
Mon Nov 1 16:55:02 CET 1999


Stuart Hungerford <stuart.hungerford at webone.com.au> writes:

> Hi all,
> 
> 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...

--

  Magnus          Echelon jamming noise:
  Lie             FBI CIA NSA Handgun Assault Bomb Drug Terrorism
  Hetland         Special Forces Delta Force AK47 Hillary Clinton 




More information about the Python-list mailing list