[Python-Dev] PEP 567 v2

Guido van Rossum guido at python.org
Wed Jan 3 00:38:07 EST 2018


On Tue, Jan 2, 2018 at 4:45 PM, Victor Stinner <victor.stinner at gmail.com>
wrote:

> 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(<default>) 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.
>

But is there a common use case? For var.get() I'd rather just pass the
default or catch the exception if the flow is different. Using ctx[var] is
rare (mostly for printing contexts, and perhaps for explaining var.get()).

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180102/f89160bf/attachment.html>


More information about the Python-Dev mailing list