[Python-Dev] PEP 567 v2 (original) (raw)

Victor Stinner victor.stinner at gmail.com
Tue Jan 2 18:45:59 EST 2018


Le 2 janv. 2018 18:57, "Guido van Rossum" <guido at python.org> a écrit :

Oh, the "Specification" section in the PEP is too brief on several of these subjects. It doesn't really specify what var.get() does if the value is not set, nor does it even mention var.get() except in the code examples for var.reset(). It's also subtle that ctx[var] returns the default (if there is one). I suppose it will raise if there isn't one -- resulting in the somewhat surprising behavior where var in ctx may be true but ctx[var] may raise. And what does it raise? (All these questions are answered by the code, but they should be clearly stated in the PEP.)

A variable has or has no default value. Would it make sense to expose the default value as a public read-only attribute (it would be equal to _NO_DEFAULT or Token.MISSING if there is no default) and/or add a is_set() method? is_set() returns true if the variable has a default value or if it was set in the "current context".

Currently, a custom sentinel is needed to check if var.get(), ctx.get(var) and ctx[var] would raise an exception or not. Example:

my_sentinel = object() is_set = (var.get(default=my_sentinel) is not my_sentinel)

no exception if is_set is true

ContextVar.get() is non obvious because the variable has an optinal default, get() has an optional default parameter, and the variable can be set or not in the current context.

Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20180103/76d16f10/attachment.html>



More information about the Python-Dev mailing list