[Python-Dev] PEP 567 pre v3
Yury Selivanov
yselivanov.ml at gmail.com
Thu Jan 11 01:58:42 EST 2018
On Thu, Jan 11, 2018 at 10:35 AM, Chris Jerdonek
<chris.jerdonek at gmail.com> wrote:
> On Mon, Jan 8, 2018 at 11:02 PM, Nathaniel Smith <njs at pobox.com> wrote:
>> Right now, the set of valid states for a ContextVar are: it can hold
>> any Python object, or it can be undefined. However, the only way it
>> can be in the "undefined" state is in a new Context where it has never
>> had a value; once it leaves the undefined state, it can never return
>> to it.
>
> I know Yury responded to one aspect of this point later on in the
> thread. However, in terms of describing the possible states without
> reference to the internal Context mappings, IIUC, wouldn't it be more
> accurate to view a ContextVar as a stack of values rather than just
> the binary "holding an object or not"? This is to reflect the number
> of times set() has been called (and so the number of times reset()
> would need to be called to "empty" the ContextVar).
But why do you want to think of ContextVar as a stack of values? Or
as something that is holding even one value?
Do Python variables hold/envelope objects they reference? No, they
don't. They are simple names and are used to lookup objects in
globals/locals dicts. ContextVars are very similar! They are *keys*
in Context objects—that is it.
ContextVar.default is returned by ContextVar.get() when it cannot find
the value for the context variable in the current Context object. If
ContextVar.default was not provided, a LookupError is raised.
The reason why this is simpler for regular variables is because they
have a dedicated syntax. Instead of writing
print(globals()['some_variable'])
we simply write
print(some_variable)
Similarly for context variables, we could have written:
print(copy_context()[var])
But instead we use a ContextVar.get():
print(var.get())
If we had a syntax support for context variables, it would be like this:
context var
print(var) # Lookups 'var' in the current context
Although I very much doubt that we would *ever* want to have a
dedicated syntax for context variables (they are very niche and are
only needed in some very special cases), I hope that this line of
thinking would help to clear the waters.
Yury
More information about the Python-Dev
mailing list