(One of my summaries of the fifth Python meetup in Leiden, NL).
Full title of the talk: memory graph: teaching tool and debugging aid in context of references, mutable data types, and shallow and deep copy.
memory_graph is a python debugging aid and teaching tool. It is a modern version of python tutor. (There is an online demo)
Python has two categories of types:
Immutable types: bool, int, float, str, tuple, etcetera. They cannot be mutated, so when a value is changed, a copy is made. If you add an item to a tuple, you get a new tuple with the extra item.
Mutable types: dicts, lists. You can change the values without the actual dict/list changing. You can add items to a list and you still have the same list object.
When you want an actual copy of a mutable type, you need to use import copy
and
copy.copy(your_list)
. And copy.deepcopy()
.
list2 = list1
is an assignment.
list2 = copy.copy(list1)
gives you a second, separate, list object, but it points
at the same values inside it as list1.
list2 = copy.deepcopy(list1)
gives you a second, separate, list object and
separate copies of the values inside it.
Watch out with the list2 = list1
assignment. When you add an item to list2, it is
also “added” to list1 as it is the same.
He had a couple of simple exercises for us, which were amusingly hard :-)
Apart from the web online demo, there are also integrations for jupyter notebooks and lots of IDEs. Here’s an animated gif from the github repo:
My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.
Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):