[Python-ideas] PEP 550 v2

Nathaniel Smith njs at pobox.com
Sat Aug 19 17:33:53 EDT 2017


On Sat, Aug 19, 2017 at 12:09 PM, Neil Girdhar <mistersheik at gmail.com> wrote:
> Cool to see this on python-ideas.  I'm really looking forward to this PEP
> 550 or 521.
>
> On Wednesday, August 16, 2017 at 3:19:29 AM UTC-4, Nathaniel Smith wrote:
>> 2) For classic decimal.localcontext context managers, the idea is
>> still that you save/restore the value, so that you can nest multiple
>> context managers without having to push/pop LCs all the time. But the
>> above API is not actually sufficient to implement a proper
>> save/restore, for a subtle reason: if you do
>>
>> ci.set(ci.get())
>>
>> then you just (potentially) moved the value from a lower LC up to the top
>> LC.
>
>
> I agree with Nathaniel that this is an issue with the current API.  I don't
> think it's a good idea to have set and get methods.  It would be much better
> to reflect the underlying ExecutionContext *stack* in the API by exposing a
> mutating *context manager* on the Context Key object instead of set.  For
> example,
>
>
> my_context = sys.new_context_key('my_context')
>
> options = my_context.get()
> options.some_mutating_method()
>
> with my_context.mutate(options):
>     # Do whatever you want with the mutated context
> # Now, the context is reverted.
>
> Similarly, instead of
>
> my_context.set('spam')
>
> you would do
>
> with my_context.mutate('spam'):
>     # Do whatever you want with the mutated context
> # Now, the context is reverted.

Unfortunately, I don't think we can eliminate the set() operation
entirely, because the libraries we want to migrate to using this --
like decimal and numpy -- generally provide set() operations in their
public API. (See: decimal.setcontext, numpy.seterr, ...) They're
generally not recommended for use in new code, but they do exist and
are covered by compatibility guarantees, so we need some way to
implement them using the PEP 550 API.

OTOH we can certainly provide a context manager like this and make it
the obvious convenient thing to use (and which also happens to do the
right thing). We could potentially also give the 'set' primitive an
ugly name to remind people that it has this pitfall, like make it
'set_in_top_context' or something.

-n

-- 
Nathaniel J. Smith -- https://vorpus.org


More information about the Python-ideas mailing list