[Python-ideas] PEP draft: context variables

Yury Selivanov yselivanov.ml at gmail.com
Tue Oct 10 12:40:41 EDT 2017

On Tue, Oct 10, 2017 at 12:34 PM, Koos Zevenhoven <k7hoven at gmail.com> wrote:
> On Tue, Oct 10, 2017 at 3:42 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> Context managers are merely syntactic sugar for try/finally statements, so
>> you can't wave your hands and say a context manager is the only supported
>> API: you *have* to break the semantics down and explain what the try/finally
>> equivalent looks like.
> Is this what you're asking?
> assi = cvar.assign(value)
> assi.__enter__()
> try:
>     # do stuff involving cvar.value
> finally:
>     assi.__exit__()

But then you *are* allowing users to use "__enter__()" and
"__exit__()" directly. Which means that some users *can* experience an
unbound growth of context values stack that will make their code run
out of memory.

This is not similar to appending something to a list -- people are
aware that lists can't grow infinitely.  But it's not obvious that you
can't call "cvar.assign(value).__enter__()" many times.

The problem with memory leaks like this is that you can easily write
some code and ship it. And only after a while you start experiencing
problems in production that are extremely hard to track.


More information about the Python-ideas mailing list