Sign in Join Now. New Post. Can open two files in a with statement: with open src as readin, open dst,"w" as writin: WRONG: comma doesn't work The comma syntax doesn't work, but is there a way, except for with open src as readin: with open dst,"w as writin Cheers, Alexy.
Follow Post Reply. Diez B. I'm not aware of any pre-defined context manager which does that. A fundamental problem though would be that the semantics become difficult. If closing the "outer" file fails, it's impossible to "rollback" the inner one. So I think it really is better to use the nested with, which makes it crystal clear that the inner block might succeed independently from the outer one.
Paul Rubin. You mean contextlib. Didn't know about that module, cool! However, the fundamental problem stays: rolling back only works if the innermost context fails. Roggisch wrote: Paul Rubin wrote: use contextlib. So now the final hurdle was that the PEP syntax:. Borrowing from PEP , it was an easy step to:. Additional discussion showed that people really liked being able to "see" the exception in the generator, even if it was only to log it; the generator is not allowed to yield another value, since the with-statement should not be usable as a loop raising a different exception is marginally acceptable.
To enable this, a new throw method for generators is proposed, which takes one to three arguments representing an exception in the usual fashion type, value, traceback and raises it at the point where the generator is suspended. Once we have this, it is a small step to proposing another generator method, close , which calls throw with a special exception, GeneratorExit.
This tells the generator to exit, and from there it's another small step to proposing that close be called automatically when the generator is garbage-collected. Then, finally, we can allow a yield-statement inside a try-finally statement, since we can now guarantee that the finally-clause will eventually be executed.
The usual cautions about finalization apply -- the process may be terminated abruptly without finalizing any objects, and objects may be kept alive forever by cycles or memory leaks in the application as opposed to cycles or leaks in the Python implementation, which are taken care of by GC. Note that we're not guaranteeing that the finally-clause is executed immediately after the generator object becomes unused, even though this is how it will work in CPython.
This is similar to auto-closing files: while a reference-counting implementation like CPython deallocates an object as soon as the last reference to it goes away, implementations that use other GC algorithms do not make the same guarantee.
Here, 'with' and 'as' are new keywords; EXPR is an arbitrary expression but not an expression-list and VAR is a single assignment target. It can not be a comma-separated sequence of variables, but it can be a parenthesized comma-separated sequence of variables.
This restriction makes a future extension possible of the syntax to have multiple comma-separated resources, each with its own optional as-clause. Here, the lowercase variables mgr, exit, value, exc are internal variables and not accessible to the user; they will most likely be implemented as special registers or stack positions. The details of the above translation are intended to prescribe the exact semantics. Similarly, if any of the calls raises an exception, the effect is exactly as it would be in the above code.
The calling convention for mgr. That is, if it returns "true", execution continues at the next statement after the with-statement, even if an exception happened inside the with-statement. However, if the with-statement was left via a non-local goto break, continue or return , this non-local return is resumed when mgr.
The motivation for this detail is to make it possible for mgr. The template in that example must commit or roll back the transaction depending on whether an exception occurred or not. Rather than just having a boolean flag indicating whether an exception occurred, we pass the complete exception information, for the benefit of an exception-logging facility for example.
Relying on sys. It was also proposed to add an additional boolean to distinguish between reaching the end of BLOCK and a non-local goto. This was rejected as too complex and unnecessary; a non-local goto should be considered unexceptional for the purposes of a database transaction roll-back decision. And allowing the original error to proceed isn't a failure. This will make both 'with' and 'as' keywords.
Without the future statement, using 'with' or 'as' as an identifier will cause a Warning to be issued to stderr. With PEP accepted, it is possible to write a decorator that makes it possible to use a generator that yields exactly once to control a with-statement.
Here's a sketch of such a decorator:. OTOH such mistakes are easily diagnosed; for example, the generator context decorator above raises RuntimeError when a second with-statement calls f. A context manager will also be added to the decimal module to support using a local decimal arithmetic context within the body of a with statement, automatically restoring the original context when the with statement is exited. The expression immediately following the with keyword in the statement is a "context expression" as that expression provides the main clue as to the runtime environment the context manager establishes for the duration of the statement body.
The code in the body of the with statement and the variable name or names after the as keyword don't really have special terms at this point in time. The general terms "statement body" and "target list" can be used, prefixing with "with" or "with statement" if the terms would otherwise be unclear. Given the existence of objects such as the decimal module's arithmetic context, the term "context" is unfortunately ambiguous. If necessary, it can be made more specific by using the terms "context manager" for the concrete object created by the context expression and "runtime context" or preferably "runtime environment" for the actual state modifications made by the context manager.
When simply discussing use of the with statement, the ambiguity shouldn't matter too much as the context expression fully defines the changes made to the runtime environment. The distinction is more important when discussing the mechanics of the with statement itself and how to go about actually implementing context managers. Many context managers such as files and generator-based contexts will be single-use objects. Requiring a fresh manager object for each with statement is the easiest way to avoid problems with multi-threaded code and nested with statements trying to use the same context manager.
It isn't coincidental that all of the standard library context managers that support reuse come from the threading module - they're all already designed to deal with the problems created by threaded and nested usage. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Please use ide. Load Comments. What's New. Most popular in Python. More related articles in Python. We use cookies to ensure you have the best browsing experience on our website.
Start Your Coding Journey Now!
0コメント