Memory

Modifying TODO items

As we’ve seen, Python allows us to modify data. Dataclasses are no exception:

> avocado_item.done = True
> avocado_item
> todo_list

We can write a function to mark items with a particular description as completed:

def complete_by_description(todo: list, descr: str):
    for item in todo:
        if item.description == descr:
            item.done = True
            return

Here we have a return statement, but we’re not returning anything. What would happen if we removed the return statement?

How would we test this function?

def test_complete_by_description():
    item1 = TodoItem(date(2019, 11, 25), "desc1", ["tag"], False)
    item2 = TodoItem(date(2019, 11, 25), "desc2", ["tag"], False)
    todo = [item1, item2]
    complete_by_description(todo, "desc1")
    assert item1.date == date(2019, 11, 25)
    assert item1.description == "desc1"
    assert item1.tags == ["tag"]
    assert item1.done
    assert item2.date == date(2019, 11, 25)
    assert item2.description == "desc2"
    assert item2.tags == ["tag"]
    assert not item2.done

Identity and equality

Imagine there’s a TODO item we really need to remember:

item1 = TodoItem(date(2020, 4, 15), "Pay taxes", ["important"], False)

We really need to remember it, so we make another copy:

item2 = TodoItem(date(2020, 4, 15), "Pay taxes", ["important"], False)

We get sick of typing it out, so we make a third copy like this:

item3 = item1
todo_list = [item1, item2, item3]

Let’s take a look at the program dictionary after we execute these statements.

Now, let’s modify item1.

> item1.description = "PAY TAXES"

What does the dictionary look like now?

Let’s create another item:

> item4 = TodoItem(date(2020, 4, 15), "Pay taxes", ["important"], False)
> item1 == item3
True
> item2 == item4
True

So we seem to have (at least) two different kinds of equality–one that seems to be about contents, and one that seems to be about identity. We can distinguish between them:

> item1 is item3
True
> item2 is item4
False

Given this, can ever have a case where:

> x == y
False
> x is y
True

Memory

The program dictionary doesn’t distinguish between these two kinds of equality–in the case above, it looks like:

name value
item1 ~TodoItem(date(2020, 4, 15), “PAY TAXES”, [“important”], False)
item2 ~TodoItem(date(2020, 4, 15), “Pay taxes”, [“important”], False)
item3 ~TodoItem(date(2020, 4, 15), “PAY TAXES”, [“important”], False)
item4 ~TodoItem(date(2020, 4, 15), “Pay taxes”, [“important”], False)

We’ll need to extend our model of Python program evaluation so that we can see these distinctions. We’ll do so by adding memory:

name value
item1 loc 1
item2 loc 2
item3 loc 1
item4 loc 3
location value
loc 1 ~TodoItem(date(2020, 4, 15), “PAY TAXES”, [“important”], False)
loc 2 ~TodoItem(date(2020, 4, 15), “Pay taxes”, [“important”], False)
loc 3 ~TodoItem(date(2020, 4, 15), “Pay taxes”, [“important”], False)

We’ll talk more about what this means next time!