如何使用Python关闭上下文管理器
标准库 open
函数既可以作为函数使用:
f = open('file.txt')
print(type(f))
<type 'file'>
也可以作为上下文管理器:
with open('file.txt') as f:
print(type(f))
<type 'file'>
我试图使用 contextlib. opening
来模仿这种行为,其中 File
code> 是我的自定义文件 I/O 类:
def my_open(filename):
f = File(filename)
f.open()
return closing(f)
这作为上下文管理器按预期工作:
with my_open('file.txt') as f:
print(type(f))
<class '__main__.File'>
但是当然,如果我直接调用,我会返回 ending
对象而不是我的对象:
f = my_open(filename)
print(type(f))
<class 'contextlib.closing'>
那么,如何做我实现了 my_open
以便它都可以作为上下文工作manager and 在直接调用时返回我的 File 对象?
github 上的完整工作示例: https://gist.github.com/1352573
The standard library open
function works both as a function:
f = open('file.txt')
print(type(f))
<type 'file'>
or as a context manager:
with open('file.txt') as f:
print(type(f))
<type 'file'>
I am trying to mimic this behaviour using contextlib.closing
, where File
is my custom file I/O class:
def my_open(filename):
f = File(filename)
f.open()
return closing(f)
this works as expected as a context manager:
with my_open('file.txt') as f:
print(type(f))
<class '__main__.File'>
but of course if I call directly, I get back the closing
object instead of my object:
f = my_open(filename)
print(type(f))
<class 'contextlib.closing'>
So, how do I implement my_open
so that it both works as a context manager and returns my File object when called directly?
Full working example on github:
https://gist.github.com/1352573
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的事情可能是自己实现 __enter__ 和 __exit__ 方法。类似这样的事情应该可以做到:
顺便说一下,在
__init__
方法中完成open
方法的工作会更惯用。The easiest thing is probably to implement the
__enter__
and__exit__
methods yourself. Something like this should do it:It would, by the way, be more idiomatic to do the work of your
open
method in your__init__
method.