Ask HN: Should Python support native Design by Contract (class invariants)?

2 points by andreamancuso ↗ HN
I recently proposed adding native support for Design by Contract to Python, starting with class invariants.

The idea: if a class defines an `__invariant__()` method, Python would automatically run it before and after every public method call. No decorators or metaclasses—just opt-in, self-verifying code.

Languages like Eiffel, D, and Ada support this natively. I tried implementing it as a C extension, but Python’s dynamic nature made that very difficult—so I brought the idea to the [official Python forum](https://discuss.python.org/t/design-by-contract-in-python-proposal-for-native-class-invariants/85434) to see if there’s broader interest.

Would love to hear what HN thinks—especially: - Have you ever wished for this in Python? - Would you use it if it were opt-in and debug-mode only? - Is Python the right place for something like this?

Link to full proposal: https://discuss.python.org/t/design-by-contract-in-python-proposal-for-native-class-invariants/85434

— Andrea

4 comments

[ 3.7 ms ] story [ 16.0 ms ] thread
This sounds like an Protocol or abstract base classes. For typing there are TypeVars.
In the worst case an class decorator can do the same.
*

1 point by andreamancuso 0 minutes ago | next | edit | delete [–]

Good point, but there’s a key difference between what abstract base classes or protocols enforce and what this proposal aims to do.

- Abstract Base Classes (ABCs) and Protocols help define interfaces and ensure that methods are implemented, but they don't automatically ensure object consistency across the class. They focus on the shape of objects, not the correctness of their internal state over time.

- This proposal for class invariants would enforce state consistency automatically after every method call, regardless of what methods are defined in the class. It’s more about ensuring that the internal state of the object is always valid (like Balance >= 0) without requiring explicit checks after every method.

As for decorators: Yes, they could technically enforce invariants, but the key point here is consistency and minimal friction. Using a decorator still requires you to opt in manually, and can lead to potential mistakes, especially when inheritance or metaclasses are involved. The goal of this proposal is to provide an explicit, built-in way to define and enforce invariants, without needing a decorator for every class or method.

(comment deleted)