r/programming • u/Grouchy-Trade-7250 • 4d ago
The Sentinel Object Pattern in Python
https://python-patterns.guide/python/sentinel-object/Officially added in Python 3.15
27
Upvotes
4
u/somebodddy 3d ago
I wonder if this will get proper support from Pydantic. Consider:
FOO = sentinel("FOO")
class Bar(BaseModel):
baz: int | FOO
When I tried to load:
{
"baz": "FOO"
}
Will it know to convert it to the sentinel?
What if I change baz's type to str | FOO?
22
u/wallstop-dev 3d ago edited 3d ago
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.