python: changing dictionary returned by groupdict()
Is it safe to modify a mutable object returned by a method of a standard library object?
Here's one specific example; but I'm looking for a general answer if possible.
#开发者_开发知识库m is a MatchObject
#I know there's only one named group in the regex
#I want to retrieve the name and the value
g, v = m.groupdict().popitem()
#do something else with m
Is this code safe? I'm concerned that by changing groupdict() I'm corrupting the object m (which I still need for later).
I tested this out, and a subsequent call to m.groupdict() still returned the original dictionary; but for all I know this may be implementation-dependent.
Generally it's only guaranteed to be safe if the documentation says so. (In this particular case it seems very unlikely that another implementation would behave differently though.)
groupdict
returns a new dictionary every time:
In [20]: id(m.groupdict())
Out[20]: 3075475492L
In [21]: id(m.groupdict())
Out[21]: 3075473588L
I cannot speak about whole standard library though. You should check yourself, whether a method returns a reference to some internally stored structure inside the object or creates a new one every time it is called. groupdict
creates a new one every time. This is why it should be safe to modify result dictionary.
You should be safe in this particular case, because MatchObject.groupdict()
returns a dictionary representing the matched groups, but it is a new copy every time.
dict.popitem()
does change the dictionary you are calling it on though.
Remove and return an arbitrary (key, value) pair from the dictionary.
popitem()
is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, callingpopitem()
raises aKeyError
.
There are two different operations being performed on m
here. The first, groupdict
, creates a dictionary from m
. The second, popitem
, returns an item from the dictionary and modifies the dictionary (but not the underlying item).
So subsequent calls to m.groupdict()
still create the dictionary from the same m
.
But why are you using popitem
at all? Why not just items()
?
精彩评论