Tuesday, January 24, 2012

mutable objects are great

TODO: pull together (find on web) a css/plugin for code snippets/syntax. Unconscionable.

You have to be careful with mutable objects in python.
Consider a structure like this:
>>> knights = { 'lancelot' : [ 1, 2, 3, 4, 5], 'robin': [1, 3, 5, 7, 9]}

In the code, say you're doing something with the list:

>>> brave =  knights.get('robin')
>>> brave.append(11)

If you then look at your dictionary, knights:
>>> print knights
{ 'lancelot' : [ 1, 2, 3, 4, 5], 'robin': [1, 3, 5, 7, 9, 11]}
When you assigned the list to brave, you're tagging the same list that lives in the dictionary, so anything you modify in it will modify the list in the dictionary as well.
Most of the time this is great, as it saves you from reassigning the list back into the dictionary after modifying it.
If you need to preserve the original list in the dictionary, make a copy:
>>> bravebrave = knights.get('robin')[:]
>>> bravebrave.append(13)
>>> print bravebrave
[1, 3, 5, 7, 9, 11, 13]
>>> print knights['robin']
[1, 3, 5, 7, 9, 11]

No comments:

Post a Comment