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

发布于 2024-12-14 07:44:54 字数 945 浏览 3 评论 0原文

标准库 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨小沫ゞ 2024-12-21 07:44:55

最简单的事情可能是自己实现 __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()

顺便说一下,在 __init__ 方法中完成 open 方法的工作会更惯用。

The easiest thing is probably to implement the __enter__ and __exit__ methods yourself. Something like this should do it:

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

   # context management
   def __enter__(self):
       return self

   def __exit__(self, *exc_info):
       self.close()

It would, by the way, be more idiomatic to do the work of your open method in your __init__ method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文