我真的很喜欢“with open('in_file'') as f”这个语法。 我想将该语法用于必须打开和关闭的我自己的资源。
但是,我不明白如何更改我的 open() 方法以启用“with”语法。 我可以(并且确实)使用 contextlib.closing() 方法,但重复使用后它变得有点笨重。
因此,我将在下面提出与 shelve.open() 有关的问题。 我不建议更改 shelve 模块,而是使用它,因为源代码对所有人来说都是现成的。
与其他需要关闭的标准库资源相比,shelve.open() 没有什么特别之处:socket.socket()、sqlite3.connect()、urllib2.urlopen() 等。
import contextlib, inspect, shelve, sys
#print(inspect.getsource(open)) # can not see how it was done here :-(
print('-' * 40)
# Given that we can view the source for the shelve module:
print(inspect.getsource(shelve))
print('-' * 40)
# Given that we can view the docs for the shelve module:
print(shelve.__doc__)
#print('-' * 40)
# Given that the desired syntax is Pythonic but is not supported:
#with shelve.open('test_shelve') as my_shelve:
# my_shelve['fact_number_1'] = "There's a dead fish on the landing."
# Given that the required syntax is convoluted and
# takes programmer attention away from the task at hand:
with contextlib.closing(shelve.open('test_shelve')) as my_shelve:
my_shelve['fact_number_2'] = "There's another dead fish on the landing."
# Q: What changes would need to made to shelve.open() to allow the
# 'with shelve.open(x) as y' syntax?
我对具有不同名称的额外包装器并不感兴趣。使用 contextlib.closing() 比这更容易、更安全、更直观。我真正感兴趣的是创建一个单独的 open() 方法,可以使用或不使用“with”来调用它。
因此,要成功回答这个问题,您需要获取 shelve 模块的源代码并显示需要对 shelve.open() 进行哪些更改才能拥有一个可以使用或不使用的单一方法'with'(如内置的 open() 或 Python3 urllib.urlopen())。
请您参考如下方法:
这里最大的问题是如果你这样做
shelf = the_function_you_want()
你想要的功能必须返回上架,但是如果你这样做
with the_function_you_want() as shelf:
您想要的函数必须返回上下文管理器。这意味着您需要返回一个也是上下文管理器的架子,这反过来意味着您需要创建一个架子子类或猴子补丁 Shelf。做一个子类可能更好:
class ContextManagerShelf(shelve.DbfilenameShelf):
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
那么你可以使用 ContextManagerShelf 作为上下文管理器,也可以不使用。签名与 shelve.open 相同。如果需要,您还可以制作一个 open 函数来配合它。
