My quarterly question on Design by Contract in Python...

Randall Hopper aa8vb at vislab.epa.gov
Tue May 11 06:52:56 EDT 1999


Stuart Hungerford:
 |> > Every so often after a minor or major Python release I like to ask
 |> > the gurus of this group about implementing Design By Contract
 |> > mechanisms (a-la Eiffel) in Python.
...
 |   Now...I wonder if it could be done with a Python pre-processor?

On that subject, is there a mechanism to "optimize away" a function call?
I'm using something like this:

  if __debug__:

    def PRE( *precond_list ):
      for precond in precond_list: assert precond, "Precondition Violation"

    def POST( *postcond_list ):
      for postcond in postcond_list: assert postcond, "Postcondition Violation"

  else:

    def PRE ( *args ): pass
    def POST( *args ): pass

In this case, if -O is given, will PRE/POST functions be generated, and
called when invoked?  Is there a way to have PRE and POST invocations
effectively be no-ops?  Ala:

  #ifdef DEBUG
  #  define PRE(x) assert(x)
  #else
  #  define PRE(x)
  #endif

Thanks,

Randall




More information about the Python-list mailing list