标准库中的open
函数既可以作为一个函数使用:
f = open('file.txt')
print(type(f))
<type 'file'>
或者作为上下文管理器:
with open('file.txt') as f:
print(type(f))
<type 'file'>
我正在尝试使用contextlib.closing
来模仿这种行为,其中File
是我的自定义文件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'>
但如果我直接调用,我会得到closing
对象而不是我的对象:
f = my_open(filename)
print(type(f))
<class 'contextlib.closing'>
那么,我该如何实现my_open
,使其既能作为上下文管理器使用,又能在直接调用时返回我的文件对象呢?
在 GitHub 上有一个完整的工作示例: https://gist.github.com/1352573
closing
的作用。当您编写with
以将任何具有close
方法的对象转换为上下文管理器时,您使用closing
。您不会提前使用它。contextlib
文档中的示例似乎非常清晰。如果您想随时将其转换为上下文管理器,则 Zach 的答案是正确的。 - agf