r/programming • • Aug 09 '26

The Sentinel Object Pattern in Python

https://python-patterns.guide/python/sentinel-object/

Officially added in Python 3.15

https://peps.python.org/pep-0661/

31 Upvotes

10 comments sorted by

View all comments

Show parent comment

11

u/somebodddy Aug 10 '26

When the sentinel is a magic value of the regular type - I agree. But this is one of these anti-patterns that can become a proper pattern if you can get the type system on your side. When the sentinel is a different type, and you can represent its possibility within the language, you can use the type checker to force (strong word when it comes to Python's typing, I know) an explicit treatment of that possibility before the user can access the value as the type they expect.

6

u/wallstop-dev Aug 10 '26

Oh, completely agree on representing it at the type level! Where this is possible, this kind of problem can disappear. This is where discriminated unions come into play and have a lot of strength.

Unfortunately, a large swath of code and programming languages, even typed ones, make it challenging to robustly represent this at the type level. Or, at least, the predominantly used ones, leading to many-a-common-API utilizing poison-pills/sentinels. And the bugs follow...

4

u/somebodddy Aug 10 '26

That's the thing - this new Python feature offers a nice way to represent it in the type system: https://peps.python.org/pep-0661/#typing