Objects & Classes

Bundling data with the code that works on it

Paolo Rota

October 16, 2026

Where we are

Since Lecture 3 (strings) and Lecture 7 (dates) you have been writing things like these:

from datetime import date

word = "grammar"
print(word.upper())                 # a method of a string

day = date(2026, 10, 16)
print(day.year, day.strftime("%A")) # an attribute and a method of a date

print(type(word), type(day))
GRAMMAR
2026 Friday
<class 'str'> <class 'datetime.date'>

type has been answering <class ...> all along. Lecture 3 promised “which values offer which methods, and why, is Lecture 8”. Today:

  1. what an object is, and what a class is;
  2. how to write your own class, and what the machine does to build an object;
  3. classes built on other classes: inheritance;
  4. polymorphism and encapsulation: one question with many answers, and data that guards itself;
  5. classes in a module, at work on a real text.

Today’s notional machine gains one piece: the object, a box that holds boxes of its own. A value’s class decides which boxes it has and what it can do.

Objects you already use

Attributes and methods

Every value in Python is an object. An object carries:

  • attributes — data stored in it, reached with a dot, no brackets: day.year;
  • methods — functions that work on it, called with a dot and brackets: day.strftime("%A"). They are stored in the object’s class.

Both are reached with a dot, so a missing one is an AttributeError either way (Lecture 3’s number.upper()).

print(day.year, day.month, day.day)        # attributes: values
print(day.weekday())                       # a method: 0 is Monday
print(day.strftime)                        # a method, NOT called
2026 10 16
4
<built-in method strftime of datetime.date object at 0x1096dcab0>

The class is the kind of thing — date, str, list. An object is one particular value of that kind: date(2026, 10, 16) is an object of class date. Also called an instance of the class.

Why make our own?

An experiment: each participant has a code, an age, and reaction times. With what we know, a dictionary, and functions next to it:

p1 = {"code": "sub-01", "age": 24, "rts": [512, 498, 540]}

def mean_rt(participant):
    total = 0
    for rt in participant["rts"]:
        total += rt
    return total / len(participant["rts"])

print(mean_rt(p1))
516.6666666666666

It works — until someone writes {"code": "sub-02", "age": 31, "rt": [...]}.

Nothing says what a participant must contain, and nothing ties mean_rt to participants. A class puts the two together: one place that says what a participant is and what you can ask it.

A class of our own

class and __init__

class Participant:
    def __init__(self, code, age):
        self.code = code            # store on THIS object
        self.age = age
        self.rts = []               # every participant starts with none

p1 = Participant("sub-01", 24)
p2 = Participant("sub-02", 31)

print(p1.code, p1.age, p1.rts)
print(p2.code, p2.age)
print(type(p1))
sub-01 24 []
sub-02 31
<class '__main__.Participant'>
  • class Participant: — a new kind of value. Class names start with a capital letter, by convention.
  • __init__ — the function that sets up each new object. You never call it: Python does, on Participant(...). The double underscores mark it as one of Python’s own names — more on those after __str__.
  • self — this very object, the one being set up. self.code = code puts a box called code inside it. Two slides on, we watch it happen.

What the machine does on Participant(...)

Participant("sub-01", 24) looks like a function call, and it is three steps:

  1. make a new, empty object of class Participant;
  2. call __init__ with self = that new object, code = "sub-01", age = 24;
  3. hand back the object — __init__ itself returns nothing.
p1 p2 a Participant a Participant code: “sub-01” age: 24 rts: [] code: “sub-02” age: 31 rts: []

An object is a box of boxes — like the module of Lecture 7. p1.age means “go to the object in p1, open its box age”. Each object has its own.

self is the new object

Step 2 says self = that new object. Let us check: __init__ prints its self, and after the call we print what landed in p1 and p2.

class Participant:
    def __init__(self, code, age):
        print("inside __init__, self is", self)
        self.code = code
        self.age = age
        self.rts = []

p1 = Participant("sub-01", 24)
print("after the call,    p1 is", p1)
p2 = Participant("sub-02", 31)
print("after the call,    p2 is", p2)
inside __init__, self is <__main__.Participant object at 0x1090aa9f0>
after the call,    p1 is <__main__.Participant object at 0x1090aa9f0>
inside __init__, self is <__main__.Participant object at 0x1096da540>
after the call,    p2 is <__main__.Participant object at 0x1096da540>

Same address, same object. self is not a copy of the object: it is the object, under a temporary name. When __init__ ends, the name self goes — a local, Lecture 5 — and the object stays, now called p1. A second call makes a new object, and self is that one.

Forgetting self

And without self? The two mistakes everybody makes once. Predict both:

class Participant:
    def __init__(code, age):   # no self
        print("setting up", code)

p1 = Participant("sub-01", 24)
TypeError: Participant.__init__() takes 2 positional arguments but 3 were given

Python always passes the new object first, so it counts 3 arguments — the object, the code, the age — and __init__ has places for 2.

class Participant:
    def __init__(self, code, age):
        code = code            # no self.
        age = age

p1 = Participant("sub-01", 24)
print(p1.code)
AttributeError: 'Participant' object has no attribute 'code'

code = code makes a local box of __init__ (Lecture 5), gone when the call ends. The object comes out empty, and the error shows up only later, at p1.code.

self in the brackets receives the object; self. before a name puts the box inside it.

Methods: functions that belong to the class

A function written inside the class is a method. Its first parameter is always self: the object it was called on.

class Participant:
    def __init__(self, code, age):
        self.code = code
        self.age = age
        self.rts = []

    def add_rt(self, rt):
        self.rts.append(rt)

    def mean_rt(self):
        total = 0
        for rt in self.rts:
            total += rt
        return total / len(self.rts)

p1 = Participant("sub-01", 24)
p1.add_rt(512)
p1.add_rt(498)
print(p1.rts, p1.mean_rt())
[512, 498] 505.0

Where does self come from?

You call p1.add_rt(540) with one argument, but the method has two parameters.
The object before the dot fills the first. Predict: does the second line work, and what is in p1.rts and p2.rts at the end?

p1.add_rt(540)                     # the usual way
Participant.add_rt(p1, 600)        # what the machine actually does

p2 = Participant("sub-02", 31)
p2.add_rt(300)                     # the same method, and now self is p2

print(p1.rts)
print(p2.rts)
[512, 498, 540, 600]
[300]

p1.add_rt(540) is shorthand for Participant.add_rt(p1, 540): find the function in the object’s class, and pass the object itself as self. That is how one method, written once, works on every participant.

Printing an object

print(p1)
<__main__.Participant object at 0x10971caa0>

Python does not know how you want a participant to look. Tell it, with another method with a double-underscore name, __str__:

class Participant:
    def __init__(self, code, age):
        self.code = code
        self.age = age
        self.rts = []

    def __str__(self):
        return f"{self.code} (age {self.age}, trials: {len(self.rts)})"

p1 = Participant("sub-01", 24)
print(p1)
sub-01 (age 24, trials: 0)

__init__ and __str__ are called by Python itself: the first by Participant(...), the second by print and by f-strings.

Double underscores: Python’s own names

Names like __init__ and __str__ — dunder names, “double under” — are never called by you. You write ordinary Python, and the machine translates it into a call of a dunder method of the value’s class:

You write Python calls
Participant("sub-01", 24) __init__, on the new object
print(p1), f"{p1}" p1.__str__()
len(word) word.__len__()
a + b a.__add__(b)
a == b a.__eq__(b)
word = "cat"
print(len(word), word.__len__())
print("2" + "3", "2".__add__("3"))
print(2 + 3, (2).__add__(3))
3 3
23 23
5 5

That is why the value decides what + does (Lecture 2): + asks the left value’s class for its __add__, and str and int each have their own. A dunder method is a hook: define it in your class, and the ordinary syntax starts working on your objects.

A list of objects

Objects go in lists like any other value — and everything from Lecture 4 works on them:

group = [Participant("sub-01", 24), Participant("sub-02", 31),
         Participant("sub-03", 19)]

for p in group:
    if p.age < 30:
        print(p)

oldest = group[0]
for p in group:
    if p.age > oldest.age:
        oldest = p
print("oldest:", oldest.code)
sub-01 (age 24, trials: 0)
sub-03 (age 19, trials: 0)
oldest: sub-02

Objects are mutable

The reference trap of Lecture 3, with objects. Predict:

a = Participant("sub-04", 40)
b = a                          # a second name, not a copy
b.age = 41

def birthday(p):
    p.age = p.age + 1          # changes the caller's object

birthday(a)
print(a.age, b.age, a is b)
42 42 True

42 42 True. One object, two names. Changing an attribute changes the object, so every name that leads to it sees the change — and so does the caller of a function that receives it (Lecture 5).

The whole class, so far

Everything so far in one place — the Participant that the inheritance slides build on:

class Participant:
    def __init__(self, code, age):
        self.code = code
        self.age = age
        self.rts = []

    def add_rt(self, rt):
        self.rts.append(rt)

    def mean_rt(self):
        total = 0
        for rt in self.rts:
            total += rt
        return total / len(self.rts)

    def __str__(self):
        return f"{self.code} (age {self.age}, trials: {len(self.rts)})"

p1 = Participant("sub-01", 24)
p1.add_rt(512)
p1.add_rt(498)
print(p1, p1.mean_rt())
sub-01 (age 24, trials: 2) 505.0

Inheritance

A class built on another

Some participants are patients: everything a participant has, plus a diagnosis. Do not copy the class — inherit from it:

class Patient(Participant):            # a Patient IS a Participant
    def __init__(self, code, age, diagnosis):
        super().__init__(code, age)    # let Participant set up its part
        self.diagnosis = diagnosis

pt = Patient("sub-05", 67, "aphasia")
pt.rts.append(830)
print(pt)                              # __str__ comes from Participant
print(pt.diagnosis)
print(isinstance(pt, Participant), isinstance(p1, Patient))
sub-05 (age 67, trials: 1)
aphasia
True False
  • Participant is the parent (or base) class, Patient the child.
  • super().__init__(...) runs the parent’s __init__ on this object, so the setup is written once.

How the machine finds pt.something

The search, in order — first match wins:

  1. the object itself (diagnosis, code, age, rts);
  2. its class, Patient (__init__);
  3. the parent class, Participant (__str__, add_rt, …);
  4. the parent’s parents, up to object, the ancestor of every class (where the default print and == come from);
  5. nothing found → AttributeError.
pt.add_rt(790)                         # found in step 3
print(pt.rts)
pt.diagnosys                           # found nowhere
[830, 790]
AttributeError: 'Patient' object has no attribute 'diagnosys'

The third lookup rule of the course, and the same shape as the other two: names in scopes (Lecture 2), modules on the search path (Lecture 7), and now attributes along the classes. An ordered search, first match wins.

Overriding a method

A child can replace a method of its parent by defining one with the same name. Predict the two lines — does the new __str__ change the participant too?

class Patient(Participant):
    def __init__(self, code, age, diagnosis):
        super().__init__(code, age)
        self.diagnosis = diagnosis

    def __str__(self):
        basic = super().__str__()            # the parent's version...
        return f"{basic}, {self.diagnosis}"  # ...plus one more piece

print(Patient("sub-05", 67, "aphasia"))
print(Participant("sub-06", 22))
sub-05 (age 67, trials: 0), aphasia
sub-06 (age 22, trials: 0)

The search starts from the object: a patient finds Patient.__str__ before it ever reaches the parent’s. A participant starts its search in Participant and never looks at Patient. Overriding changes the child only.

Polymorphism

One question, many answers

You have met this since Lecture 2: the value decides what an operation does.

print(len("cat"), len([1, 2, 3, 4]), len({"a": 1}))
print(2 + 3, "2" + "3")
3 4 1
5 23

Your classes can join in: different classes, same method name, each with its own answer. One loop, one print(p) — predict the two lines:

group = [Participant("sub-01", 24), Patient("sub-05", 67, "aphasia")]
for p in group:
    print(p)
sub-01 (age 24, trials: 0)
sub-05 (age 67, trials: 0), aphasia

Polymorphism: many shapes. The loop asks every object the same thing, and each one answers in its own way. Adding a new kind of participant needs no change to the loop.

Encapsulation

The object guards its own data

A new version of Participant, with rts renamed _rts. Its add_rt refuses impossible values: under 100 ms is too fast for a real response, so it counts as an anticipation. MIN_RT is a class attribute, one box in the class (step 2 of the lookup):

class Participant:
    MIN_RT = 100                     # one value shared by the whole class

    def __init__(self, code, age):
        self.code = code
        self.age = age
        self._rts = []               # _ : "internal, use the methods"

    def add_rt(self, rt):
        if rt < Participant.MIN_RT:
            return False             # refused
        self._rts.append(rt)
        return True

    def n_trials(self):
        return len(self._rts)

p = Participant("sub-01", 24)
print(p.add_rt(512), p.add_rt(87), p.n_trials())
True False 1

The underscore is a convention

The underscore in _rts is a message to other programmers: “do not touch this from outside — use the methods”. Python does not enforce it:

p._rts.append(5)                   # allowed... and now the data are wrong
print(p.n_trials(), p._rts)
2 [512, 5]

Encapsulation means the class decides how its data may change: through its methods, which check. A leading _ marks what is internal. Respect it in other people’s classes, and use it in yours.

The classic trap: a list in the class

MIN_RT lives in the class, shared by every participant. So why not the list of trials too? Each session should start with none — predict the last line:

class Session:
    trials = []                      # in the class, not in __init__

    def __init__(self, code):
        self.code = code

    def add(self, rt):
        self.trials.append(rt)

s1 = Session("sub-01")
s2 = Session("sub-02")
s1.add(512)
print(s1.trials, s2.trials, s1.trials is s2.trials)
[512] [512] True

trials is a class attribute: one box, in the class. Neither object has a trials of its own, so the lookup finds the class’s at step 2, for both — and append changes that one shared list. Fix: self.trials = [] inside __init__, one new list per object. Constants in the class; anything you fill or change, in __init__.

Objects for text

A Book class, in a module

The read_book of Lecture 6, packed into an object that remembers its lines and can give you its words. A class lives in a module like a function does (Lecture 7), so it goes in texts.py:

# texts.py
"""Gutenberg books as objects."""


class Book:
    """A Gutenberg book: its lines, without the licence."""

    def __init__(self, path):
        self.lines = []
        inside = False
        with open(path, "r", encoding="utf-8") as f:
            for line in f:
                if line.startswith("*** END OF"):
                    break
                if inside:
                    self.lines.append(line.strip())
                if line.startswith("*** START OF"):
                    inside = True

    def words(self):
        """Return every word, lower-cased, without outer punctuation."""
        result = []
        for line in self.lines:
            for w in line.split():
                w = w.lower().strip(".,;:!?()\"'“”‘’-—")
                if w != "":
                    result.append(w)
        return result

Using the Book

In main.py, in the same folder:

# main.py
from collections import Counter
from texts import Book

alice = Book("resources/mini_alice.txt")

print(len(alice.lines), "lines,", len(alice.words()), "words")
print(Counter(alice.words()).most_common(3))
(intro2python) $ python main.py
8 lines, 62 words
[('the', 4), ('of', 3), ('or', 3)]

main.py reads like the task: open the book, count its words, give me the top three. How the licence is skipped or the punctuation removed lives in one place, inside the class — and the class in one file, texts.py.

What to take away

  1. A class is a kind of value; an object (instance) is one value of that kind. Attributes hold its data, methods are its functions.
  2. __init__(self, ...) sets up each new object; self is that object, and self.x = ... stores on it. Dunder methods (__init__, __str__, __len__, …) are called by Python for you.
  3. obj.method(a) is Class.method(obj, a): the object becomes self.
  4. Inheritance: class Child(Parent):, super().__init__(...); lookup goes object → class → parent.
  5. Polymorphism: same method name, each class its own answer. Encapsulation: _internal, change data through methods.
  6. Constants in the class; lists and anything else you change, in __init__. Classes live in modules, like functions.

Try it now

Two names, one object?

Predict the four lines:

class Box:
    def __init__(self, value):
        self.value = value

a = Box(1)
b = Box(1)
c = a
c.value = 2

print(a.value, b.value, c.value)
print(a is c, a is b)
print(a.value == c.value)
print(b == Box(1))
2 1 2
True False
True
False

Two names, one object? — answer

2 1 2 — c = a made a second name for the same object, so changing c.value changed a’s too; b is a different object.

True False — is asks “the same object?” (Lecture 3).

True — the two values are both 2.

False — Box(1) builds a new object, and for our own classes == means “the same object” unless the class says otherwise.

Which error?

Each line uses the Participant class with add_rt and n_trials. Name what happens — error or not. One click per answer.

p = Participant("sub-01", 24)
print(p.n_trials)
<bound method Participant.n_trials of <__main__.Participant object at 0x1096dbb00>>
print(p.age_years)
AttributeError: 'Participant' object has no attribute 'age_years'
q = Participant("sub-02")
TypeError: Participant.__init__() missing 1 required positional argument: 'age'

No error, but no call: without brackets you get the method itself · AttributeError: no such box, on the object or in its class · TypeError: __init__ needs code and age.

Which __str__, which sound?

Predict the three lines:

class Animal:
    def __init__(self, name):
        self.name = name
    def sound(self):
        return "..."
    def __str__(self):
        return f"{self.name} says {self.sound()}"

class Dog(Animal):
    def sound(self):
        return "woof"

class Puppy(Dog):
    def __str__(self):
        return "a small " + super().__str__()

for a in [Animal("Rex"), Dog("Fido"), Puppy("Bea")]:
    print(a)
Rex says ...
Fido says woof
a small Bea says woof

Which __str__, which sound? — answer

Rex says ... — everything is found in Animal.

Fido says woof — __str__ is found in Animal, the parent. Inside it, self is still Fido, so self.sound() starts the search from the object again: Dog has a sound, and wins.

a small Bea says woof — __str__ is found in Puppy; super().__str__() runs Animal’s, and sound is found in Dog, Puppy’s parent.

Exercises

Exercise 1 — Rectangle

Write a class Rectangle:

  • __init__(self, length, width) stores the two sides;
  • area() returns the area, perimeter() the perimeter;
  • __str__ returns something like "Rectangle 5 x 3".
r = Rectangle(5, 3)
print(r, r.area(), r.perimeter())     # Rectangle 5 x 3 15 16

Exercise 1 — solution

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * self.length + 2 * self.width

    def __str__(self):
        return f"Rectangle {self.length} x {self.width}"

r = Rectangle(5, 3)
print(r, r.area(), r.perimeter())
Rectangle 5 x 3 15 16

The methods read the sides from self, so the same area works for every rectangle you build.

Exercise 2 — Square, by inheritance

Write a class Square that inherits from your Rectangle and takes a single side. It must reuse area() and perimeter() without rewriting them, and print as "Square 5".

s = Square(5)
print(s, s.area(), s.perimeter())     # Square 5 25 20
print(isinstance(s, Rectangle))       # True

Exercise 2 — solution

class Square(Rectangle):
    def __init__(self, side):
        super().__init__(side, side)      # a square: both sides equal

    def __str__(self):
        return f"Square {self.length}"

s = Square(5)
print(s, s.area(), s.perimeter())
print(isinstance(s, Rectangle))
Square 5 25 20
True

super().__init__(side, side) lets Rectangle store length and width; area and perimeter are then found in Rectangle by the lookup. Only __str__ is overridden.

Exercise 3 — Age on a given day

Write a class Person with name, country and born (a date). Add a method age_on(on) that returns the person’s age in whole years on the day on, also a date.

from datetime import date
ada = Person("Ada", "UK", date(2000, 12, 10))
print(ada.age_on(date(2026, 10, 16)))     # 25 — the birthday is not here yet
print(ada.age_on(date(2026, 12, 10)))     # 26

Careful: subtracting the years is not enough.

Exercise 3 — solution

from datetime import date

class Person:
    def __init__(self, name, country, born):
        self.name = name
        self.country = country
        self.born = born

    def age_on(self, on):
        age = on.year - self.born.year
        before_month = on.month < self.born.month
        same_month_before_day = on.month == self.born.month and on.day < self.born.day
        if before_month or same_month_before_day:
            age = age - 1                     # birthday not reached yet
        return age

ada = Person("Ada", "UK", date(2000, 12, 10))
print(ada.age_on(date(2026, 10, 16)), ada.age_on(date(2026, 12, 10)))
print(ada.age_on(date.today()))
25 26
25

Passing the day in, instead of always using date.today(), makes the method testable: the first two calls give the same answer every year.

Exercise 4 — A bank account

Write a class Account that keeps its money in _balance, starting at 0:

  • deposit(amount) adds; it refuses amounts that are not positive;
  • withdraw(amount) subtracts; it refuses amounts that are not positive, or larger than the balance;
  • both return True if they did it, False if they refused;
  • balance() returns the current balance.
acc = Account()
print(acc.deposit(100), acc.withdraw(30), acc.withdraw(500))  # True True False
print(acc.deposit(-5))                                       # False
print(acc.balance())                                         # 70

Exercise 4 — solution

class Account:
    def __init__(self):
        self._balance = 0

    def deposit(self, amount):
        if amount <= 0:
            return False
        self._balance = self._balance + amount
        return True

    def withdraw(self, amount):
        if amount <= 0 or amount > self._balance:
            return False
        self._balance = self._balance - amount
        return True

    def balance(self):
        return self._balance

acc = Account()
print(acc.deposit(100), acc.withdraw(30), acc.withdraw(500))
print(acc.deposit(-5))
print(acc.balance())
True True False
False
70

Every change of _balance goes through a method that checks it first, and True / False tells the caller whether it happened.

Exercise 5 — A corpus

Write corpus.py, next to the texts.py of the slides, with a class Corpus that uses Book:

  • __init__(self) starts with no books;
  • add(path) reads a book and keeps it;
  • n_words() returns the total number of words in all the books;
  • most_common(n) — the n most common words over all the books.

Test it from main.py by adding resources/mini_alice.txt twice: the counts must double.

Exercise 5 — solution

# corpus.py
"""Several books, counted together."""
from collections import Counter
from texts import Book


class Corpus:
    """A collection of Book objects."""

    def __init__(self):
        self.books = []

    def add(self, path):
        """Read the book at path and keep it."""
        self.books.append(Book(path))

    def all_words(self):
        """Return the words of every book, in one list."""
        words = []
        for book in self.books:
            words = words + book.words()
        return words

    def n_words(self):
        return len(self.all_words())

    def most_common(self, n):
        return Counter(self.all_words()).most_common(n)

A Corpus holds Book objects and asks them for their words: it never opens a file itself. all_words is a helper the other two methods share.

Exercise 5 — solution, run

# main.py
from corpus import Corpus

corpus = Corpus()
corpus.add("resources/mini_alice.txt")
print(corpus.n_words(), corpus.most_common(2))
corpus.add("resources/mini_alice.txt")
print(corpus.n_words(), corpus.most_common(2))
(intro2python) $ python main.py
62 [('the', 4), ('of', 3)]
124 [('the', 8), ('of', 6)]

Three files, one job each: texts.py knows books, corpus.py knows collections of books, main.py knows the task.

Exercise 6 — Trials from a file

resources/trials.json holds the trials of a lexical decision task: a word or a pseudo-word on screen, a key press, a reaction time.

[
  {
    "word": "table",
    "condition": "real",
    "rt": 512,
    "correct": true
  },
  ...
]

In trials.py:

  1. a class Trial with word, condition, rt, correct, and a method is_valid(): correct and rt of at least 100 ms;
  2. a function load_trials(path) that returns a list of Trial objects from the file.

In main.py: print, for real and for pseudo, the mean rt of the valid trials.

Exercise 6 — solution (1/2)

# trials.py
"""The trials of a lexical decision task."""
import json


class Trial:
    """One trial: the word shown, its condition, the response."""

    def __init__(self, word, condition, rt, correct):
        self.word = word
        self.condition = condition
        self.rt = rt
        self.correct = correct

    def is_valid(self):
        """True if answered correctly, and not an anticipation."""
        return self.correct and self.rt >= 100


def load_trials(path):
    """Return the trials in the JSON file at path, as Trial objects."""
    with open(path, "r", encoding="utf-8") as f:
        rows = json.load(f)
    trials = []
    for row in rows:
        trials.append(Trial(row["word"], row["condition"], row["rt"], row["correct"]))
    return trials

load_trials turns each dictionary from the file into an object: from here on, the rest of the program never touches the raw dictionaries.

Exercise 6 — solution (2/2)

# main.py
from trials import load_trials

trials = load_trials("resources/trials.json")

for condition in ["real", "pseudo"]:
    total = 0
    n = 0
    for t in trials:
        if t.condition == condition and t.is_valid():
            total += t.rt
            n += 1
    print(f"{condition:<7}{total / n:.1f} ms over {n} trials")
(intro2python) $ python main.py
real   505.0 ms over 2 trials
pseudo 682.0 ms over 3 trials

t.is_valid() keeps the rule in one place: change the 100 ms in trials.py and every program that uses it follows.

Questions?