强制使用上下文管理器?

发布于 2025-02-02 12:40:47 字数 858 浏览 2 评论 0原文

我有一个定义为类的自定义资源来管理该资源。这种组合正常工作。有什么方法可以强制使用该资源仅通过上下文管理器使用,如果有任何东西,那是Pythonic?

更新:

我已经测试了一个想法,似乎工作正常。但是我不确定,这是否是一个好主意,我自己没有发现任何缺点。想检查Python专家的意见。

想法:由于我的资源是一种自定义资源,因此我在其中包括了一张支票,以确保其由资源管理器管理。

class Resource:
    def __init__(self, name, resource_manager):
        rm = isinstance(resource_manager, ResourceManager)
        if not rm:
            raise Exception("Resource must be managed by the resource manager")
        else:
            ........
            ........
            ........

在资源经理中,我正在做以下类似的事情:

class ResourceManager:
    def __init__(self, resource_name):
        self.resource = Resource(resource_name, self)
    def __enter__(self):
        return self.resource
    def __exit__(self, type, value, traceback):
        ......
        ......

I have a custom resource defined as a class and a context manager to manage that resource. This combination is working perfectly. Is there any way to enforce that the resource will be used through context manager only and if anything is there then is that Pythonic?

Update:

I have tested one idea what seems to be working perfectly. But I am not very sure, whether this is a good idea or not, though, I haven't found any drawback by my own. Wanted to check the opinion of the python experts.

Idea: As my resource is a custom resource, I have included a check there to ensure it is getting managed by a resource manager.

class Resource:
    def __init__(self, name, resource_manager):
        rm = isinstance(resource_manager, ResourceManager)
        if not rm:
            raise Exception("Resource must be managed by the resource manager")
        else:
            ........
            ........
            ........

And in the resource manager, I am doing something like below:

class ResourceManager:
    def __init__(self, resource_name):
        self.resource = Resource(resource_name, self)
    def __enter__(self):
        return self.resource
    def __exit__(self, type, value, traceback):
        ......
        ......

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

与酒说心事 2025-02-09 12:40:47

简短答案:不,您不能强制使用上下文管理。

长答案: 在使用实例时已选中的上下文管理器设置状态,并且未能设置该状态会引起异常。如果对象没有其他方法,则它将无法使用。您可以做的另一件事是具有状态,该状态指示该对象是否已通过__退出__,并使用 警告模块在没有__ ex e退出__ exit __的情况下,将resource-warnning提高resource-code>被称为。这可以通过实现__ del __或使用 figref.finalize ,当对象收集到垃圾时,两者都可以执行最终检查。

至于“ Pythonic”,我能告诉您的最好的是,垃圾收集技巧上的Resource Warnning是Python本身在未正确关闭打开的文件手柄时使用的信息,可以通过<<代码> __退出__ 或通过关闭方法,在收集它们之前。这不是一个完美的解决方案(默认警告过滤器永远不会告诉您Resource-Warning s,因此您的用户必须选择加入),但是除非上下文管理是唯一的合理的方式要使用您的班级(不寻常的;甚至可以以上下文管理无法覆盖的方式合理地使用它),这是最好的方法:低开销,不在乎的人的低语,但对于开发人员来说是可见的谁需要调试问题。

Short answer: No, you can't force use of context management.

Long answer: You could have entering the context manager set state on the instance that is checked whenever the instance is used, and have failure to set that state raise an exception. It won't work if the object has no other methods called though. The other thing you can do is have state that indicates if the object has been cleaned by __exit__, and use the warnings module to raise a ResourceWarning when the object is garbage-collected without __exit__ being called. This can be done either by implementing __del__ or by using weakref.finalize, either of which can perform final checks when the object is garbage-collected.

As far as what's "Pythonic", the best I can tell you is that the ResourceWarning on garbage-collection trick is what Python itself uses to inform people when open file handles are not properly closed, either via __exit__ or via the close method, before they are collected. It's not a perfect solution (the default warnings filter never tells you about ResourceWarnings, so your users have to opt-in), but unless context management is the only reasonable way to use your class (unusual; even file objects can reasonably be used in ways that context management can't cover), it's the nicest way to do it: Low overhead, low verbosity for people who don't care, but visible to developers who need to debug issues.

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