TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

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

2 pointsby andreamancusoabout 2 months ago
I recently proposed adding native support for Design by Contract to Python, starting with class invariants.<p>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.<p>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:&#x2F;&#x2F;discuss.python.org&#x2F;t&#x2F;design-by-contract-in-python-proposal-for-native-class-invariants&#x2F;85434) to see if there’s broader interest.<p>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?<p>Link to full proposal: https:&#x2F;&#x2F;discuss.python.org&#x2F;t&#x2F;design-by-contract-in-python-proposal-for-native-class-invariants&#x2F;85434<p>— Andrea

1 comment

stop50about 2 months ago
This sounds like an Protocol or abstract base classes. For typing there are TypeVars.
评论 #43433933 未加载