I really fell in love with constexpr in c++.
I know Python doesn’t have anything like C++’s constexpr today, but I’ve been wondering if it’s even possible (or desirable) for the language to get something similar.
In C++, you can mark a function as constexpr so the compiler evaluates it at compile time:
constexpr int square(int x) { if (x < 0) throw « negative value not allowed »; return x * x; } constexpr int result = square(5); // OK constexpr int bad = square(-2); // compiler/ide error here
The second call never even runs — the compiler flags it right away.
Imagine if Python had something similar:
@constexpr def square(x: int) -> int: if x < 0: raise ValueError(« negative value not allowed ») return x * x result = square(5) # fine bad = square(-2) # IDE/tooling flags this immediately
Even if it couldn’t be true compile-time like C++, having the IDE run certain functions during static analysis and flag invalid constant arguments could be a huge dev experience boost.
Has anyone seen PEPs or experiments around this idea?
submitted by /u/uname_IsAlreadyTaken to r/Python
[link] [comments]
Laisser un commentaire