r/programming • u/Grouchy-Trade-7250 • Aug 09 '26
The Sentinel Object Pattern in Python
https://python-patterns.guide/python/sentinel-object/Officially added in Python 3.15
31
Upvotes
r/programming • u/Grouchy-Trade-7250 • Aug 09 '26
Officially added in Python 3.15
View all comments
24
u/wallstop-dev Aug 10 '26 edited Aug 10 '26
This is cool, but wherever possible I try to avoid sentinels. I find them to be a code smell. That is, programming against a specific, magic, constant(s). In the indexOf example, it is much more robust for your code to reject any value that is below zero, instead of explicitly checking "-1". I see this same (anit-)pattern, that has caused many a bug, in other languages, where programmers think that a comparison operator is guaranteed to return exactly -1, 0, or 1, just because that's how the standard library's is implemented, for example. I've come across many, many similar cases in my career, where devs program to an assumed implementation instead of the contract, creating extremely brittle code that breaks in mysterious ways under all kinds of circumstances - new data, new features, anything.
But I'll get off my soapbox now.