2

I saw following code from here.

d[key] = data # store data at key (overwrites old data if # using an existing key) data = d[key] # retrieve a COPY of data at key (raise KeyError if no # such key) 

I don't understand the meaning of doing so. It is said retrieve a COPY of data at key. Seems dict lookup (getitem, or indexing, which one is the proper term?) will make a cope of the object? Right?

0

3 Answers 3

5

You're seeing shelve module documentation.

shelve.open returns a dictionary-like object, not a dictionary. It does not load all key-value pair at once; so comments in the example make sense.

Sign up to request clarification or add additional context in comments.

Comments

3

Ordinarily, dict lookup returns the value stored at the key, not a copy of the value. This is important for mutable objects. For instance:

A = dict() A["a"] = ["Hello", "world"] # Stores a 2-element list in the dict, at key "a" B = A["a"] # Gets the list that was just stored B[0] = "Goodbye" # Changes the first element of the list print(A["a"][0]) # Prints "Goodbye" 

In contrast, shelve will return a copy of the value stored with the key, so changing the returned value will not change the shelved value.

Comments

0

You are confusing implementation (i.e. what __getitem__ does for one specific type of object) for a specification (i.e. a prescription for what __getitem__ should do all the time).

__getitem__ just implements syntactic sugar around x[i] - it places no demands on how that is actually done. x[i] could just return the value associated with i in a dictionary. It could return a copy. It could cause way more side effects - i.e. it could cause files to be created/deleted, databases to be connected/disconnected, objects to be created/deleted, etc.

For dict, __getitem__ is defined to return the original object. But you shouldn't assume those semantics will apply for all other objects that implement it - you will be disappointed. When in doubt, you are doing the right thing - check the docs.

2 Comments

I appreciate your answer with very clear and definitive phrasing. What I actually want to know is about the implementation of the built-in type dict.
OK, that's much clearer. If you do mydict = {}; x = <something>; mydict['x'] = x, then x and mydict['x'] point to the same object; it returns the original reference, not a copy. Also, I should point that this is the 'normal' behaviour - most of the time when objects implement __getitem__, it's like dict, and stores references. In the above, one reason shelve mentions COPY in 'bold' is because it is less common, and so worth mentioning.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.