【问题标题】:Why can you use open() as context manager?为什么可以使用 open() 作为上下文管理器?
【发布时间】:2017-05-03 10:12:52
【问题描述】:

从Python的source code of open来看,我认为open只是一个普通的函数。

为什么我们可以像下面这样使用它?

with open('what_are_context_managers.txt', 'r') as infile:
    for line in infile:
        print('> {}'.format(line))

因为既不实现__enter__ 也不实现__exit__,也不使用contextlib.contextmanager 装饰器。

【问题讨论】:

  • 函数返回的原始file类型实现了上下文管理器接口。

标签: python contextmanager


【解决方案1】:

您没有将open 函数用作上下文管理器。 open(...) 调用表达式的结果是上下文管理器。 open() 返回一个文件对象,该对象具有__enter____exit__ 方法;见io.IOBase documentation:

IOBase 也是一个上下文管理器,因此支持 with 语句。

您可以像这样阅读with 声明:

_context_manager = open('what_are_context_managers.txt', 'r')
with _context_manager as infile:

请注意,_context_manager.__enter__() 的返回值最终在此处被分配给 infile。对于文件对象,file.__enter__() 返回self,因此您可以通过这种方式访问​​同一个对象。


作为旁注;你弄错了open() 函数。内置open() 的实际定义是io.open() 的别名,请参见_iomodule.c source code。别名在initstdio() in pylifecycle.c 中设置(其中io.OpenWrapperitself an alias for _io.open)。是的,文档说明别名指向另一个方式,以方便最终用户使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2022-09-27
    • 1970-01-01
    • 2021-01-28
    • 2020-06-08
    • 1970-01-01
    相关资源
    最近更新 更多