r/Python • • Jun 06 '21

News PEP 661 -- Sentinel Values

https://www.python.org/dev/peps/pep-0661/
220 Upvotes

109 comments sorted by

View all comments

Show parent comment

3

u/genericlemon24 Jun 10 '21

If that's the sentinel, and the user chose to supply it, why is that a problem? [...] If you want a sentinel that reads as "<NotGiven>" and the user is allowed to read that in debug output, then why aren't they allowed to pass it as an argument?

The user doesn't supply the sentinel, that's set when you write the function. The user supplies the default value.

The sentinel can read "<NotGiven>" in the debug output; However, it can't be the "<NotGiven>" string; that is, it can, but because of the identity thing mentioned before, you won't be able to tell it apart from the sentinel.*

You can restrict the valid values to exclude "<NotGiven>". In your own code you may be able to guarantee it's never a valid value. But as a library author, you can never foresee all the use cases – maybe there's a crazy user out there that needs to use "<NotGiven>". And you'd have to document it, and the users would always need to be aware of it (which isn't really friendly, IMHO).


* (the identity thing, with more details)

Due to string (possible) interning, subsequent ast.literal_eval("'<NotGiven>'") calls may result in the same object; or not. (ast.literal_eval("<NotGiven>") (no quotes) does not result in a valid value, because <NotGiven> is not a valid literal.)

From the data model docs:

Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed.