[Python-ideas] PEP 550 v2

Guido van Rossum guido at python.org
Wed Aug 23 11:41:06 EDT 2017


On Wed, Aug 23, 2017 at 2:00 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> On 21 August 2017 at 07:01, Barry <barry at barrys-emacs.org> wrote:
> > I'm not clear why there is a new_context_key which seems not to be a key.
> > It seems that the object is a container for a single value.
> >
> > Key.set( value ) does not feel right.
>
> It's basically borrowed from procedural thread local APIs, which tend
> to use APIs like "tss_set(key, value)".
>
> That said, in a separate discussion, Caleb Hattingh mentioned C#'s
> AsyncLocal API, and it occurred to me that "context local" might work
> well as the name of the context access API:
>
>     my_implicit_state = sys.new_context_local('my_state')
>     my_implicit_state.set('spam')
>
>     # Later, to access the value of my_implicit_state:
>     print(my_implicit_state.get())
>
> That way, we'd have 3 clearly defined kinds of local variables:
>
> * frame locals (the regular kind)
> * thread locals (threading.locals() et al)
> * context locals (PEP 550)
>
> The fact contexts can be nested, and a failed lookup in the active
> implicit context may then query outer namespaces in the current
> execution context would then be directly analogous to the way name
> lookups are resolved for frame locals.


If we're extending the analogy with thread-locals we should at least
consider making each instantiation return a namespace rather than something
holding a single value. We have

log_state = threading.local()
log_state.verbose = False

def action(x):
    if log_state.verbose:
        print(x)

def make_verbose():
    log_state.verbose = True

It would be nice if we could upgrade this to make it PEP 550-aware so that
only the first line needs to change:

log_state = sys.AsyncLocal("log state")
# The rest is the same

We might even support the alternative notation where you can provide
default values and suggest a schema, similar to to threading.local:

class LogState(threading.local):
    verbose = False

log_state = LogState(<description>)

(I think that for calls that construct empty instances of various types we
should just use the class name rather than some factory function. I also
think none of this should live in sys but that's separate.)

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170823/0326731c/attachment-0001.html>


More information about the Python-ideas mailing list