any chance for contracts and invariants in Python?

Philipp Hagemeister phihag at
Thu Feb 14 18:03:04 CET 2013

I don't know anything about the status of this PEP or why it hasn't been
implemented, but here's what strikes me as obviously complex:

Doesn't one need to traverse the entire class hierarchy on every
function call? So if I have

class A:
  def foo(self):
    return 1

class B(A):
  "inv: True"
  def foo(self):
    "post: __return__ == 2"
    return 2

Now, I have
f = B().foo
. What does Python do?

If your answer is
1. Look up class of f
2. Check its invariant (succeeds)
3. Execute the function
4. Check post conditions of f (succeeds)
5. return 2

Then what will I get if I run any of the following programs: = 'inv: __return__ == 1'

def _foo(self):
  'post: __return__ == 3' = _foo

A.__doc__ = 'inv: False'

So any implementation has to choose one of the following:

1. Ignore invariants and postconditions of inherited classes - defeats
the purpose.
2. Only respect definitions in classes and methods in the original
definition, which would be unpythonic
3. Only respect the "original" definitions, for some value of original.
Simarily, this would break monkey patching.
4. Update all subclasses whenever something changes.
5. Traverse the entire class hierarchy for every method call.

Which option should be picked?

Additionally, the reference implementation is not actually a fork of
cpython (or a metaclass), but a Python script that - as far as I
understand - I have to call manually to start using contracts.

- Philipp

On 14.02.2013 12:42, mrkafk at wrote:
> This PEP seems to be gathering dust:
> I was thinking the other day, would contracts and invariants not be better than unit tests? That is, they could do what unit tests do and more, bc they run at execution time and not just at development time?

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: OpenPGP digital signature
URL: <>

More information about the Python-list mailing list