【问题标题】:shelve module does not work with "with" statement搁置模块不适用于“with”语句
【发布时间】:2017-08-20 22:41:09
【问题描述】:

我正在尝试在 python 中使用 shelve 模块,并尝试将其与“with”语句结合使用,但是在尝试这样做时出现以下错误:

with shelve.open('shelve', 'c') as shlv_file:
    shlv_file['title']    = 'The main title of my app'
    shlv_file['datatype'] = 'data type int32'
    shlv_file['content']  = 'Lorem ipsum'
    shlv_file['refs']     = '<htppsa: asda.com>'

print(shlv_file)

出现以下错误:

 with shelve.open('shelve', 'c') as shlv_file:
AttributeError: DbfilenameShelf instance has no attribute '__exit__'

虽然这样做:

shlv_file = shelve.open('data/shelve', 'c')
shlv_file['title']    = 'The main title of my app'
shlv_file['datatype'] = 'data type int32'
shlv_file['content']  = 'Lorem ipsum'
shlv_file['refs']     = '<htppsa: asda.com>'
shlv_file.close()

shlv_file = shelve.open('data/shelve', 'c')
shlv_file['new_filed'] = 'bla bla bla'
print(shlv_file)

没有引发错误,并且输出是预期的。第一种语法有什么问题?我在看一个python课程,讲师使用第一个版本没有任何问题。

【问题讨论】:

  • 你的 Python 版本是多少?根据the documentation,在 3.4 中添加了上下文管理器支持(with 块)。

标签: python persistence shelve


【解决方案1】:

您需要了解with 的用途。它基本上用于自动处理调用对象的设置和清理,前提是这些对象支持使用此类设置和清理函数。特别是,setup 的对象是__enter__ 函数,而teardown 等效的是__exit__ 函数。这是一个例子:

In [355]: class Foo():
     ...:     def __enter__(self):
     ...:         print("Start!")
     ...:         return self
     ...:     def __exit__(self, type, value, traceback):
     ...:         print("End!")
     ...:         

并且,现在用with...as 实例化Foo 的对象:

In [356]: with Foo() as x:
     ...:     print(x)
     ...:     
Start!
<__main__.Foo object at 0x1097f5da0>
End!

如您所见,with...as 将强制调用这些 setup/teardown 方法,如果它们丢失,则会引发 AttributeError,因为尝试调用不存在的实例方法。

您的 shelve 对象也是如此 - 它没有在其类中定义 __exit__ 方法,因此使用 with 将不起作用。


根据documentation,从 3.4 及更高版本开始添加对上下文管理器的支持。如果上下文管理器不起作用,则意味着您的版本较旧。

【讨论】:

  • 我明白你的解释。我仍然感到困惑的是,为什么它似乎在我正在观看的讲师教程上运行良好,而在我的机器上却无法运行?
  • +1 用于解释,但 shelve 在最近的版本(3.4+)中确实支持上下文管理器,这就是为什么 Pj- 可能在教程中看到它。
  • @PauloAlmeida 感谢您注意到这一点。我不知道shelve,所以我只是假设它没有实现。
  • @Pj- 正如 Paulo 所指出的,这与您的 python 版本有关。
  • 我认为我的python版本不是最新的。我会试试@PauloAlmeida
猜你喜欢
  • 1970-01-01
  • 2012-08-15
  • 2020-07-28
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
相关资源
最近更新 更多