Documentation of dict views change request

C

Charles Hixson

Could it please be clearly documented that keys(), values(), and items()
are not writeable. I agree that this is how they should be, but it
would be still better if they were clearly documented as such. The
labeling of them as dynamic, while true, was a bit confusing here.
(I.e., it was talking about changing their value through other means of
access rather than directly through the returned values.)

P.S.: Is it reasonable to return the items() of a dict in order to pass
a read only copy of the values?
 
R

Roy Smith

Charles Hixson said:
Could it please be clearly documented that keys(), values(), and items()
are not writeable.

We'll, technically, they are.
d = {'foo': 1, 'bar':2}
k = d.keys()
k ['foo', 'bar']
k[0] = "some other key"
k
['some other key', 'bar']

Of course, this only changes the list that keys() returns, it doesn't
affect the dictionary itself (which, I assume, is what you were really
talking about).

Think this one through. How *could* altering what keys() returns
possibly affect the dict? If it did, that means you could do something
like:

some_dict.keys().append("some other key")

what would that mean? You've added a key, but what's the corresponding
value? I will admit, the picture becomes a bit fuzzier if you consider:

some_dict.items().append(("some other key", 42))

which you could at least imagine would affect the underlying dict.
 
C

Chris Angelico

We'll, technically, they are.

Of course, this only changes the list that keys() returns, it doesn't
affect the dictionary itself (which, I assume, is what you were really
talking about).

In Python 3, they return views, not lists. So they really are read-only.

P.S.: Is it reasonable to return the items() of a dict in order to pass a
read only copy of the values?

No, because it isn't a copy. At least, not in Python 3; if you're
using Python 2, then the wording of your subject line is inaccurate,
see above.
d = {"a":1,"b":2,"c":3}
i = d.items()
del d["b"]
list(i)
[('a', 1), ('c', 3)]

If you returned i from a function and expected it to be a copy, you'd
be in for a nasty shock. Try the .copy() method for a shallow copy, or
look up deepcopy if you need a recursive copy.

ChrisA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top