Python for Databases 3: Objects and Generator Expressions
A minimal class turns a table row into an object, and a generator expression asks a question about many objects in one line: the two ideas behind object-relational mapping.
Last updated:
How can a table row become an object, and a question about many rows become one expression?
An ORM (object-relational mapper) is a tool that lets you work with database tables as if they were Python objects:
a class stands for a table, an object stands for a row, and a question about rows is written as a Python expression.
This lesson teaches the two Python ideas behind that: a very small class, and the generator expression.
The ORM lesson then uses both ideas to read and change database rows from Python.
The lesson continues the earlier ones: values and collections and loops and functions.
The boxes of this page share their variables, so run them from top to bottom.
We start with the same six rows of the bike-share table.
rows = [
(1, '2011-01-01', 'Winter', 985),
(2, '2011-01-02', 'Winter', 801),
(3, '2011-01-03', 'Winter', 1349),
(185, '2011-07-04', 'Summer', 6043),
(186, '2011-07-05', 'Summer', 4665),
(187, '2011-07-06', 'Summer', 4629),
]
len(rows)
6
Objects, attributes and methods
Every value in Python is an object: a value that carries its own data and its own functions.
You already used the functions of objects: message.upper() and rides.append(1700) are methods, functions that belong to an object and are written after a dot.
The data that an object carries are its attributes, also written after a dot:day.rentals would be the attribute rentals of the object day.
A dictionary reads a value with a key, day['rentals']. An object reads it with a dot, day.rentals.
The dot is shorter, and it is how an ORM lets you read a column of a row, so rows from a database can be used with the same style.
The question is how to get an object that has the attributes date, season and rentals:
for that we define a class.
Practice
Your turn. Create the list rides = [985, 801], add 1349 to it with the method rides.append, and print rides.
A method is a function that belongs to the value before the dot.
# your code here
Show a solution
rides = [985, 801]
rides.append(1349)
print(rides)
[985, 801, 1349]
Show a common mistake and why it happens
The method append changes the list in place and returns None.
Assigning its result to rides replaces the list with None:
rides = [985, 801]
rides = rides.append(1349)
print(rides)
A class: a template for objects
A class is a template that describes a kind of object: which attributes it has.
Every object of the class, called an instance, has its own values for these attributes.
A class stands for a table, and each object stands for a row.
The smallest way to write such a class in Python uses dataclasses, a module (a bundle of ready-made tools) that offers dataclass.
The line @dataclass above a class asks Python to write the set-up code for us.
Because of it, we can create objects by naming the attributes, as in the keyword arguments of loops and functions:
from dataclasses import dataclass
@dataclass
class Day:
date: str
season: str
rentals: int
Read the definition from the top:
class Day:starts the definition of a new kind of object calledDay. The indented lines are its body. A class name starts with a capital letter, by convention.- Each line in the body names an attribute and its type,
rentals: int. The type is for readers: Python does not check it.
Now we create objects and read and change their attributes:
first = Day(date='2011-01-01', season='Winter', rentals=985)
print(first.date, first.rentals)
first.rentals = 990
print(first)
print(
Day(
date='2011-07-04', season='Summer', rentals=6043
).season
)
2011-01-01 985
Day(date='2011-01-01', season='Winter', rentals=990)
Summer
Each call such as Day(...) creates a new object with its own values.
Assigning to an attribute, first.rentals = 990, changes that object only.
With @dataclass, printing an object shows the class name and its attributes.
To build one object for every row of a table, loop over the rows and collect the objects in a list.
The ORM does this for you, but the code shows what happens:
days = []
for day_id, date, season, rentals in rows:
days.append(
Day(date=date, season=season, rentals=rentals)
)
print(len(days), days[3].date, days[3].rentals)
6 2011-07-04 6043
Check yourself: first.rentals is 990, and these lines run:
second = Day(
date='2011-01-02', season='Winter', rentals=801
)
second.rentals = second.rentals + 100
What do first.rentals and second.rentals hold?
A: first.rentals is 990 and second.rentals is 901
Correct: each object keeps its own values. The line changes the attribute of second only, from 801 to 901, and first stays 990.
B: both are 901
The thinking: the class is shared by both objects, so a change applies to all of them.
The mistake: the class is only the template. The values live in the objects, one set for each object, so a change in one object does not touch another.
C: an error, because an attribute cannot be changed after the object is created
The thinking: an object behaves like a tuple.
The mistake: a tuple cannot be changed, but the attributes of an object of our class can, as the line first.rentals = 990 showed.
Only a class that is declared as frozen refuses changes, and ours is not.
Practice
Your turn. Create an object my_day of the class Day with the date 2011-03-05, the season Spring and 2000 rentals, and print its three attributes, date, season and rentals, in this order, one on each line.
# your code here
Show a solution
my_day = Day(date='2011-03-05', season='Spring', rentals=2000)
print(my_day.date)
print(my_day.season)
print(my_day.rentals)
2011-03-05
Spring
2000
Show a common mistake and why it happens
print(my_day) prints the whole object in one line, with the class name, instead of the three attributes one on each line:
my_day = Day(date='2011-03-05', season='Spring', rentals=2000)
print(my_day)
Show a common mistake and why it happens
One print with three values writes them on a single line, separated by spaces.
The task asks for one line for each attribute:
my_day = Day(date='2011-03-05', season='Spring', rentals=2000)
print(my_day.date, my_day.season, my_day.rentals)
List comprehensions and generator expressions: a question about many objects in one line
How many rentals were there in the summer rows? With a loop we would write four lines.
Python has a short form, a list comprehension, that says “the value of this expression, for each item of the collection, where a condition holds”:
[d.rentals for d in days]
[985, 801, 1349, 6043, 4665, 4629]
[d.rentals for d in days if d.season == 'Summer']
[6043, 4665, 4629]
A list comprehension has square brackets, an expression, for and a name, and optionally if and a condition.
Read the second box as: “the rentals d.rentals, for every d in days, if the season of d is Summer”.
The expression comes first, then the loop, and then the condition.
Write the same thing with round brackets, and you get a generator expression.
It does not build a list. It is a recipe that produces the values one at a time, when something asks for them.
The function next asks for the next value, and list collects all the values that are left:
summer = (d.rentals for d in days if d.season == 'Summer')
print(next(summer), next(summer))
print(list(summer))
print(list(summer))
6043 4665
[4629]
[]
After two values, list(summer) collects what is left, and a generator can be used only once, so the second list(summer) is empty.
When a generator expression is the only argument of a function, you can omit the extra brackets, and the function consumes the values:
print(sum(d.rentals for d in days if d.season == 'Summer'))
print(max(d.rentals for d in days))
print(sum(1 for d in days if d.rentals > 1000))
print(sorted((d.rentals for d in days), reverse=True)[:2])
15337
6043
4
[6043, 4665]
The last line sorts the rentals from the largest to the smallest and keeps the first two.
The extra round brackets there belong to the generator expression, because it is not the only argument of sorted.
Practice
Your turn. Print the list of the dates of the winter days of days, using an expression in square brackets.
# your code here
Show a solution
print([d.date for d in days if d.season == 'Winter'])
['2011-01-01', '2011-01-02', '2011-01-03']
Show a common mistake and why it happens
Without the condition if d.season == 'Winter', the list holds the dates of every day, not only the winter days:
print([d.date for d in days])
Show a common mistake and why it happens
The value at the start of the expression decides what goes into the list.d.rentals collects the rentals, but the task asks for the dates:
print([d.rentals for d in days if d.season == 'Winter'])
From a generator expression to SQL
A generator expression and a query ask the same thing, in two languages.
The parts correspond:
| Part of the Python expression | Part of the SQL query |
|---|---|
the value at the start: d.rentals | the columns after SELECT |
for d in days | the table after FROM |
if d.season == 'Summer' | the condition after WHERE |
sorted(..., key=..., reverse=True) | ORDER BY ... DESC |
sum(...), max(...), and sum(1 for ...) to count | SUM, MAX, COUNT |
A generator expression can also be written about a class that stands for a table, for example with the ORM function select, which takes such an expression and runs it as a database query.
This is a preview, and nothing in this lesson needs it:
select(d for d in Day if d.season == 'Summer')
The ORM does not run the expression in Python. It reads it and translates it into a query like:
SELECT * FROM Day WHERE season = 'Summer'
The database then runs that query. That is why this lesson spends time on the form of the expression.
Practice
Each question has its own code box: write your answer there and select Run.
Open a hint if you are stuck, and the solution only after you try.
Question 1. Create an object d of the class Day for the row below and print its date.
(3, '2011-01-03', 'Winter', 1349)
# your answer here
Show a solution
d = Day(date='2011-01-03', season='Winter', rentals=1349)
print(d.date)
2011-01-03
Show a common mistake and why it happens
print(d) shows the class name and all the attributes. To print the date, read the attribute:d.date:
d = Day(date='2011-01-03', season='Winter', rentals=1349)
print(d)
Question 2. Write one expression with sum that gives the total rentals of the winter days in days.
# your answer here
Show a hint
The same form as the summer example: replace the season in the condition.
Show a solution
sum(d.rentals for d in days if d.season == 'Winter')
3135
Show a common mistake and why it happens
Without if d.season == 'Winter', the expression adds the rentals of every day, not only the winter days:
sum(d.rentals for d in days)
Question 3. Write an expression that gives the list of dates of the days with more than 4000 rentals.
# your answer here
Show a hint
You need a list, so use square brackets, or call list on a generator expression.
The value at the start is d.date.
Show a solution
[d.date for d in days if d.rentals > 4000]
['2011-07-04', '2011-07-05', '2011-07-06']
Show a common mistake and why it happens
The part before for says what each item of the list is. Here it is d.rentals; the task asks for d.date:
[d.rentals for d in days if d.rentals > 4000]
Question 4. In SQL we would write:
SELECT date FROM Day WHERE rentals > 4000
Mark in the list expression below the part that matches each SQL part:
[d.date for d in days if d.rentals > 4000]
Show a solution
d.date at the start is SELECT date; for d in days is FROM Day; if d.rentals > 4000 is WHERE rentals > 4000.
Keep in mind
-
Values are objects: they have methods (
text.upper()) and attributes (day.rentals), both written after a dot. -
A class is a template for objects. With
@dataclass, a class lists its attributes, and objects are created with named arguments, for example:Day(date='2011-01-01', season='Winter', rentals=985)A class stands for a table and an object stands for a row.
-
A list comprehension is written like this:
[expression for item in collection if condition]It builds a list; with round brackets it is a generator expression that produces values one at a time and can be used once.
-
sum,max,min,sortedandlisttake a generator expression directly. -
The three parts of such an expression correspond to
SELECT,FROMandWHERE, so an ORM can translate a Python expression into SQL and the database does the work.