A
A
Andrey Nosov2016-04-25 16:38:58
Python
Andrey Nosov, 2016-04-25 16:38:58

Why doesn't the Shelve module work in Python 3?

Good afternoon. There is a piece of code:

import shelve

data = shelve.open("quiz")
data["quiz1"] = {"theme" : None}
data["quiz1"]["theme"] = "Cinematograph"
print(data["quiz1"]["theme"])
data.close()

I am writing in Python 3.5.1 . With the print()
function , the interpreter prints None , even though the library had assigned a value to this key in the line above. What am I doing wrong? It is worth adding that I study the language from the book "Programming in Python" by M. Dawson and use the module as he explained.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2016-04-25
@tde283

Look. data is a file handle that mimics the behavior of a dictionary. It has a __setattr__ method that is called directly when you write the "square brackets" operator with equality. In your case:
data['key'] = {'this': 'is dict'}
The datatype of data is shelve
The datatype of data['key'] is a dictionary
When you write this:
data["quiz1"][" theme"] = "Cinematograph"
the __setattr__ method is called on the data["quiz1"] dictionary
and it has nothing to do with shelve. Therefore, in order to do what you want, you need to rewrite it somehow like this:

import shelve

data = shelve.open("quiz")
data["quiz1"] = {"theme" : None}
tmp = data["quiz1"]
tmp["theme"] = "Cinematograph"
data["quiz1"] = tmp
print(data["quiz1"]["theme"])
data.close()

Or open shelve with the key writeback=True: data = shelve.open('quiz', writeback=True)
But writeback must be used carefully:
By the way, this is written in the documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question