Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对于with嵌套如何优化 #46

Closed
shihuizhen opened this issue Jun 28, 2020 · 2 comments
Closed

对于with嵌套如何优化 #46

shihuizhen opened this issue Jun 28, 2020 · 2 comments

Comments

@shihuizhen
Copy link

感谢作者的分享,优美的文笔,恰当的例子,让我觉得我以前写的不是python。

对于with嵌套作者有没有好的优化思路?写代码的时候遇到要打开多个文件,嵌套好几层with获取 文件对象,感觉很丑。

@piglei
Copy link
Owner

piglei commented Jun 28, 2020

你好,普通的写法就是全部摊开来,比如:

with open('foo.txt') as f1, open('bar.txt') as f2:
    ...

也可以使用 contextlib.ExitStack 。文档里就有一个示例:


For example, a set of files may easily be handled in a single with statement as follows:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a with statement). Note that callbacks are not invoked implicitly when the context stack instance is garbage collected.

@shihuizhen
Copy link
Author

谢谢作者。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants