如何在Python中处理在另一个上下文管理器中创建的上下文管理器?
示例:假设您具有A
充当上下文管理器的类B
,以及充当上下文管理器的类.但是类B
实例必须实例化并使用类的实例A
.我已经通过了PEP 343,这是我想到的解决方案:
class A(object):
def __enter__(self):
# Acquire some resources here
return self
def __exit__(seplf, exception_type, exception, traceback):
# Release the resources and clean up
pass
class B(object):
def __init__(self):
self.a = A()
def __enter__(self):
# Acquire some resources, but also need to "start" our instance of A
self.a.__enter__()
return self
def __exit__(self, exception_type, exception, traceback):
# Release the resources, and make our instance of A clean up as well
self.a.__exit__(exception_type, …
Run Code Online (Sandbox Code Playgroud) Python教我们使用__enter__
和对对象进行清理__exit__
.如果我需要创建一个使用对象的对象,必须使用上下文管理器怎么办?想象一下:
from database1 import DB1
from database2 import DB2
Run Code Online (Sandbox Code Playgroud)
通常情况下,他们会这样使用:
with DB1() as db1, DB2() as db2:
db1.do_stuff()
db2.do_other_stuff()
Run Code Online (Sandbox Code Playgroud)
无论发生什么,db1
并db2
都将运行自己的__exit__
功能,并清理连接,同花顺等
当我把所有这些都放在课堂上时,我该怎么做?这是正确的吗?这显然是不正确的,正如评论中所指出的那样,上下文管理器db1
并db2
在块的末尾运行.
class MyApp(object):
def __enter__(self):
with DB1() as self.db1, DB2() as self.db2:
return self
def __exit__(self, type, value, traceback):
self.db1.__exit__(self, type, value, traceback)
self.db2.__exit__(self, type, value, traceback)
Run Code Online (Sandbox Code Playgroud)
我甚至考虑过做这样的事情:这看起来是个好主意,实际上(经过一些清理):
class MyApp(object):
def __init__(self):
self.db1 = DB1()
self.db2 = DB2()
def __enter__(self):
self.db1.__enter__()
self.db2.__enter__()
return …
Run Code Online (Sandbox Code Playgroud) 我有一个 Python 中的 C++ 代码生成器,可以生成许多源文件。大多数时候,只有一个文件发生变化,但由于生成器会重新生成所有文件,因此它们都会被重建。有没有办法让Python不覆盖文件,或者让cmak使用校验和来查看需要重建的内容,而不仅仅是使用文件日期?
我在想这样的事情在Python中会很容易:如果我可以替换
with open('blah', 'w') as f:
Run Code Online (Sandbox Code Playgroud)
有了这个:
with open_but_only_overwrite_if_total_output_is_different('blah', 'w') as f:
Run Code Online (Sandbox Code Playgroud)
实现这一目标的好方法是什么?