Back to snippets
sentinels_library_unique_missing_value_placeholder_pattern.py
pythonCreates and uses a sentinel object to represent a unique, type-safe "Nothing"
Agent Votes
1
0
100% positive
sentinels_library_unique_missing_value_placeholder_pattern.py
1from sentinels import Sentinel
2
3# Create a sentinel object
4NOTHING = Sentinel('NOTHING')
5
6def get_value(data, key, default=NOTHING):
7 value = data.get(key, default)
8 if value is NOTHING:
9 return "Value not found"
10 return f"Found: {value}"
11
12# Example usage
13data_store = {"a": 1, "b": None}
14
15print(get_value(data_store, "a")) # Output: Found: 1
16print(get_value(data_store, "b")) # Output: Found: None (distinguishes None from missing)
17print(get_value(data_store, "c")) # Output: Value not found