Feature suggestions: "Using declarations" i.e. context managers ("with" blocks) tied to scope/lifetime of the variable rather than to nesting

Neil Cerutti neilc at norwich.edu
Tue Feb 19 10:42:00 EST 2019

On 2019-02-19, mnl.post at gmail.com <mnl.post at gmail.com> wrote:
> I thought this new C# feature would be a good thing to add to Python:
> https://vcsjones.com/2019/01/30/csharp-8-using-declarations/
> I find the nesting required by context managers to be at odds with the
> broad intent.
> The code indentation in python should reflect the program logic and
> flow as much as possible, but for thing, the context manager generally
> doesn't apply to most of the code it forces to be indented, but only
> to a few lines using the resource; for another, even for those lines,
> the context manager is usually not reflective of the flow anyway
> (unlike the classic control statements, such as for/next, if/else, and
> while).
> for example:
> with xxxxxx.open() as logfile:
>      do this
>      do that
>      logfile.write()
>      do this
>      do that
>      logfile.write()
> This becomes more ugly if multiple withs get nested.

You don't have to nest them. Check out contextlib.ExitStack.
ExitStack is designed to handle situations where you don't always
want to enter some context, or you are entering a large number of

Neil Cerutti

More information about the Python-list mailing list