HACKER Q&A
📣 andreamancuso

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


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


  👤 stop50 Accepted Answer ✓
This sounds like an Protocol or abstract base classes. For typing there are TypeVars.