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

mnl.post at gmail.com mnl.post at gmail.com
Thu Feb 21 13:35:53 EST 2019


(I sent this a few days ago but got bounced without a reason—don’t see it
posted, so I’m trying one more time.)


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/

The nesting required by context managers can be at odds with a program’s
real structure.  The code indentation in python should reflect the program
logic and flow as much as possible, but for one 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()
     with xxxx as dbs_conn:
          do this
          do that
          logfile.write()
Things like dbs_conn are functioning as just a variable (albeit one wants
assurance its object will be determinstically destroyed)—the indentation
reflects the span of lines the variable is being used (held open), but
shouldn’t change the structure for that reason.

(This is uglier as additional withs get nested.)



More information about the Python-list mailing list