如何使用Python关闭上下文管理器

And*_*nca 7 python file-io with-statement

标准库open函数既可以作为函数使用:

f = open('file.txt')
print(type(f))
<type 'file'>
Run Code Online (Sandbox Code Playgroud)

或作为上下文管理者:

with open('file.txt') as f:
    print(type(f))
<type 'file'>
Run Code Online (Sandbox Code Playgroud)

我试图模仿这种行为contextlib.closing,File我的自定义文件I/O类在哪里:

def myopen(filename):
    f = File(filename)
    f.open()
    return closing(f)
Run Code Online (Sandbox Code Playgroud)

这可以像上下文管理器一样工作:

with myopen('file.txt') as f:
    print(type(f))
<class '__main__.File'>
Run Code Online (Sandbox Code Playgroud)

但是当然如果我直接打电话,我会收回closing对象而不是我的对象:

f = myopen(filename)
print(type(f))
<class 'contextlib.closing'>
Run Code Online (Sandbox Code Playgroud)

那么,我myopen该如何实现它以便它既作为上下文管理器直接调用时返回我的File对象?

github上的完整工作示例:https: //gist.github.com/1352573

zwo*_*wol 13

最简单的事情可能是自己实现__enter____exit__方法.这样的事情应该这样做:

class File(object):
   # ... all the methods you already have ...

   # context management
   def __enter__(self):
       return self
   def __exit__(self, *exc_info):
       self.close()
Run Code Online (Sandbox Code Playgroud)

顺便说一句,在您的open方法中执行__init__方法的工作会更加惯用.