python - shelve module does not work with "with" statement -
i'm trying use shelve module in python, , i'm trying combine "with" statement, when trying following error:
with shelve.open('shelve', 'c') shlv_file: shlv_file['title'] = 'the main title of app' shlv_file['datatype'] = 'data type int32' shlv_file['content'] = 'lorem ipsum' shlv_file['refs'] = '<htppsa: asda.com>' print(shlv_file)
the following error raised:
shelve.open('shelve', 'c') shlv_file: attributeerror: dbfilenameshelf instance has no attribute '__exit__'
although doing way:
shlv_file = shelve.open('data/shelve', 'c') shlv_file['title'] = 'the main title of 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)
no error raised, , output 1 expected. problem first syntax ? watching python course in instructor uses first version without problems.
you need understand purpose of with
used for. used automatically handle setup , cleanup of objects called with, provided those objects support use of such setup , cleanup functions. in particular, object setup __enter__
function, , teardown equivalent __exit__
function. here's example:
in [355]: class foo(): ...: def __enter__(self): ...: print("start!") ...: return self ...: def __exit__(self, type, value, traceback): ...: print("end!") ...:
and, instantiate object of foo
with...as
:
in [356]: foo() x: ...: print(x) ...: start! <__main__.foo object @ 0x1097f5da0> end!
as see, with...as
compulsorily call these setup/teardown methods, , if they're missing, attributeerror
raised because attempt call non-existent instance method made.
it's same shelve
object - doesn't have __exit__
method defined in class, using with
not work.
according documentation, support context manager added version 3.4 , onwards. if context manager not work, mean version older.
Comments
Post a Comment