Objects are the star of the show
Remember: variables point to objects
Variables point to objects in Python. But variables don’t contain objects; variables just point to objects.
Objects are the star of the show in Python.
With that in mind, how could we improve this function?
def characters(string):
"""Return list of all characters in given string, lowercased."""
case_normalized = string.casefold()
character_list = list(case_normalized)
return character_list
We could refactor the code to remove that variable that’s returned.
def characters(string):
"""Return list of all characters in given string, lowercased."""
case_normalized = string.casefold()
return list(case_normalized)
That final variable points to an object and then we immediately return that object. We don’t really need that variable.
In fact, we don’t even need the other variable:
def characters(string):
"""Return list of all characters in given string, lowercased."""
return list(string.casefold())
We shouldn’t remove all variables from our code though. Some variables are helpful and some are even essential.
When do we absolutely need a variable?
Within the global scope or within a class to name an object so that it can be used later
Within a function, when an object needs to be referenced multiple times (for example, to mutate the object in a loop)
When Python’s syntax requires a variable (function names, class names, for loop items, etc.)
When are variables useful (even when not strictly necessary)?
To use tuple unpacking, so that we can use descriptive names instead of hard-coded indexes
To clarify the purpose of an object returned from a function call or another operation
Both of those unnecessary but nonetheless useful variable use cases boil down to:
To give a descriptive name to something when the purpose of a value isn’t otherwise obvious
Objects contain pointers
Let’s point a variable (row) to a list of three zeroes:
>>> row = [0, 0, 0]
Now let’s make a new variable (boat) that points to a list of lists:
>>> boat = [row, row, row]
We now have a list of three lists, each with three zeros inside it:
>>> boat
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
What we happen if we look up index 1 and then index 1 again and change that to 1?
>>> boat[1][1] = 1
What do you think might happen? What will change in our lists?
We’re looking up the second list and then the second value in that list and we’re assigning that value to 1.
We’ve asked to change the middle item in the middle list to the number 1.
That’s not quite what happens:
>>> boat
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
Instead, we changed the middle number in all three of our inner lists!
Why did this happen?
Well…
Lists in Python don’t actually contain objects. They contain references to objects.
And when we made our outer list, we gave it 3 references to the same list:
>>> id(boat[0])
139699039162432
>>> id(boat[1])
139699039162432
>>> boat[0] is boat[1]
True
Python’s data structures contain pointers to objects, not the objects themselves.
If we look at our row list, we’ll see that it also changed:
>>> row
[0, 1, 0]
We’ve talked about the fact that variables in Python are not like buckets containing objects. Instead, variables point to objects.
Python’s data structures are also not buckets containing objects. Instead, data structures refer to objects. Which means one object can be pointed to by multiple variables, multiple data structures, or even the same data structure multiple times.
So our boat list stores three pointers to the same list.
When we “changed” one of our inner lists, we mutated that list (one of our two types of change in Python).
But since we store a reference to the same list three times, it seemed like we changed three lists.
Avoiding accidental references
If we wanted to avoid this issue of referring to the same list multiple times, we could have copied our row list:
>>> row = [0, 0, 0]
>>> boat = [row.copy(), row.copy(), row.copy()]
Or we could have just manually created 3 equivalent lists:
>>> boat = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Either way, changing one of the three sublists won’t change the others because they’re all independent lists:
>>> boat[1][1] = 1
>>> boat
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
These are different lists stored in different parts of Python’s memory:
>>> boat[0] is boat[1]
False
>>> id(boat[0])
140660999377344
>>> id(boat[1])
140660999379648
An ouroboros list
Data structures contain references to objects, but not the objects themselves.
This append call is the ultimate demonstration of this fact:
>>> x = []
>>> x.append(x)
We’ve taken a list and stuck that list inside of itself.
At this point the first (and only) element of this list is the list itself:
>>> x[0] is x
True
And the first element of that list is also the list itself:
>>> x[0][0] is x
True
And the first element of that list is also the list itself:
>>> x[0][0][0] is x
True
It’s one list… all the way down.
We’ve made an infinitely recursive data structure:
>>> x[0][0][0][0][0] is x
True
Python represents this list at the Python prompt by putting three dots inside those square brackets (it’s smart enough not to show an infinite number of square brackets):
>>> x
[[...]]
We didn’t stick a bucket inside itself here because that’s impossible.
Data structures don’t contain other objects. They just contain a reference to an object.
Our list contains a pointer that refers back to the same list. Lists only store pointers, not objects. And they’re allowed to store pointers to anything, even themselves.
Little contracts everywhere
Most operations in Python are powered by one or more dunder methods.
Dunder stands for double underscore. This is an unofficial term for methods that have two underscores on either side.
The Python documentation refers to these as special methods, but the term dunder method is often used colloquially.
When Python evaluates an expression that involves using an operator between two objects, it will attempt to call a dunder method on the first object and it may also attempt to call a dunder method on the second object.
Let’s look at an example with the infix + operator (using + between two objects).
When Python evaluates the + operator between two objects, it attempts to call the __add__ method on the first object:
>>> n = 2
>>> m = 2.5
>>> n + m
4.5
>>> n.__add__(m)
NotImplemented
If that object doesn’t have a __add__ method or if that method call returned NotImplemented then it will call the __radd__ method on the second object:
>>> m.__radd__(n)
4.5
If that method returns a value besides NotImplemented, then that’s the value Python uses.
If that __radd__ method doesn’t exist or NotImplemented was returned by it, then a TypeError exception would be raised.
Contracts for everything
Infix operators are not the only Python feature that relies on dunder methods.
Many built-in functions rely on one or more dunder methods:
>>> n = 4
>>> str(n)
'4'
>>> n.__str__()
'4'
Item lookups rely on dunder methods:
>>> colors = ["purple", "blue", "yellow"]
>>> colors[0]
'purple'
>>> colors.__getitem__(0)
'purple'
Attribute lookups do too:
>>> from types import SimpleNamespace
>>> x = SimpleNamespace(a=4, b=5)
>>> x
namespace(a=4, b=5)
>>> x.a
4
>>> x.__getattribute__("a")
4
And so do for loops, with blocks, equality checks, function calls, and pretty much any other operation you think of.
Object Exercises
These exercises are all in the objects.py file in the exercises directory. Edit the file to fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py split_in_half
Split in Half
This code works, but it is a bit of a mess: it has lots of variables, which makes it cluttered and rather difficult to read. Clean up the code.
def split_in_half(sequence):
"""Return two halves of the given sequence."""
length = len(sequence)
half_way = length // 2
first_half = sequence[:half_way]
second_half = sequence[half_way:]
combined = (first_half, second_half)
return combined
It should work like this:
>>> from objects import split_in_half
>>> split_in_half([1, 2, 3, 4])
([1, 2], [3, 4])
>>> split_in_half([1, 2, 3, 4, 5])
([1, 2], [3, 4, 5])
>>> split_in_half([1, 2])
([1], [2])
>>> split_in_half([])
([], [])
>>> split_in_half([1])
([], [1])
Try your function on other iterables (strings or tuples). Does it still work?
>>> from objects import split_in_half
>>> split_in_half("Hello world!")
('Hello ', 'world!')
>>> split_in_half((1, 2))
((1,), (2,))
Vote Tally
Write a function get_vote_tally that takes a multi-line string where each line contains a name and numbers representing voted choices.
The function should return a list of tuples, where each tuple contains a vote count and the options chosen that had that vote count.
The returned list should be sorted in descending order of vote counts.
Here’s an example of how it should work:
>>> from objects import get_vote_tally
>>> get_vote_tally("Victor: 1 3 4\nPaul: 1 3\nAlex: 2 3 4\nMildred: 2 4\n")
[(3, [3, 4]), (2, [1, 2])]
That list of tuples represents the fact that options 3 and 4 each received 3 votes and options 1 and 2 each received 2 votes.
Here’s a broken implementation of this function. Figure out what’s broken and how to fix it.
from collections import Counter
import re
def get_vote_tally(text):
counts_to_choices = Counter(re.findall(r"\d+", text))
tally_groups = dict.fromkeys(counts_to_choices.values(), set())
for choice, count in counts_to_choices.most_common():
tally_groups[count].add(int(choice))
return [
(count, sorted(choices))
for count, choices in tally_groups.items()
]
Flavor
Here we have a class Flavor to represent flavors of ice cream.
Unfortunately, it does not pass the tests.
Refactor the class to make it pass the tests.
class Flavor:
"""Flavor of ice cream."""
def __init__(self, name, ingredients=[], has_dairy=True):
self.name = name
self.ingredients = ingredients
self.has_dairy = has_dairy
def __contains__(self, ingredient):
"""Return True if the given ingredient is in this flavor."""
return ingredient in self.ingredients
def __repr__(self):
return (
f"{type(self).__name__}(name={self.name!r},"
f" ingredients={self.ingredients},"
f" has_dairy={self.has_dairy})"
)
It should work like this:
>>> from objects import Flavor
>>> vanilla = Flavor("vanilla")
>>> vanilla.name
'vanilla'
>>> vanilla.has_dairy
True
>>> vanilla.ingredients
[]
>>> vanilla
Flavor(name='vanilla', ingredients=[], has_dairy=True)
>>> mint_chip = Flavor(
... name="mint chip",
... ingredients=["sugar", "mint", "cashews", "coconut milk"],
... has_dairy=False,
... )
>>> mint_chip.ingredients
['sugar', 'mint', 'cashews', 'coconut milk']
>>> mint_chip.has_dairy
False