DS 208 · Week 4

Modular Programming

Keeping a program readable once it exceeds a single notebook cell, using classes, error handling and files that import each other.

Programming for Data Science · University of the Philippines Cebu

Outline

Three tools for larger programs

Previous session

From loading data to structuring code

Week 3 covered lists, dictionaries and reading files, which fill a notebook quickly. Structure prevents it from becoming a long sequence of tangled cells.

The problem

Copy-pasted logic and very long cells become difficult to fix or trust.

The remedy

Group related data and behaviour, guard against bad input, and split into files.

About the tool

Classes were invented in Norway in the 1960s

1967

Simula 67

Ole-Johan Dahl and Kristen Nygaard introduce objects, classes and inheritance.

1991

Python 0.9

Python’s first public release already has classes and exception handling.

2001

Turing Award

Dahl and Nygaard receive computing’s highest prize for the idea.

SourceWikipedia: Simula; History of Python

About the tool

Where classes appear in everyday Python

SourcePython Language Reference, §3.1 Objects, values and types; Built-in Exceptions

Key terms · 1 of 2

Seven terms for Part A: classes

class

A blueprint that describes what one kind of thing holds and what it can do. Analogy: a cookie cutter.

e.g. class Student: starts the blueprint for a student

object (instance)

One actual thing built from a class (one cookie from the cutter). “Instance” means the same thing.

e.g. ana = Student("2024-001", "Ana") makes one student object

attribute

A value stored on an object. It is read with a dot and no brackets.

e.g. ana.name gives 'Ana'

method

A function that lives inside a class and works on that object’s own data. Called with a dot and ( ).

e.g. ana.average() works out Ana’s mean grade

self

Inside a class, the name for “this particular object”. Python fills it in automatically.

e.g. self.name = name stores the name on this object

__init__

The set-up method Python runs automatically each time a new object is created. Pronounced “dunder init” (double underscore).

e.g. Student("2024-001", "Ana") implicitly runs __init__

inheritance

Making a new class from an existing one: it gets everything the parent class has, then adds or changes a little.

e.g. class DiscountedSale(Sale): is a Sale, with a discount

Key terms · 2 of 2

Six terms for Parts B and C: errors and files

exception

Python’s report that something went wrong while running. It stops the program unless the code handles it.

e.g. ValueError, KeyError, IndexError

traceback

The error printout. It shows the route Python took; the last line names the error type and message.

e.g. last line ValueError: invalid literal for int()

try / except

Try a risky line; if a named exception happens, run the except block instead of crashing.

e.g. try: int(raw) … except ValueError: score = 0

raise

Stop deliberately and report an exception, with a custom message.

e.g. raise ValueError("out of range: 130")

module

A .py file of code that other files can import (bring in) and reuse.

e.g. grades.py, then from grades import average

package

A folder of modules that Python can import from, marked by a file called __init__.py.

e.g. a src/ folder holding load.py and clean.py

Part A

Classes & objects

Data and behaviour, bundled into one thing.

A function groups steps (week 2) and a dictionary groups values (week 3). A class does both at once: it keeps the values and the functions that use them together.

Motivation

Keeping related values together

A student has a number, a name, and grades. Passing three separate variables (named boxes) everywhere is fragile. A class is a blueprint for one kind of thing. Each thing built from it is an object (also called an instance) that keeps those values together — with its own methods (functions that belong to it).

A class is a cookie cutter and each object is one cookie; every cookie has the same shape but its own toppings, so Ana’s grades are not Ben’s grades.

A function

Groups behaviour: inputs in, output out.

A class

Groups data + behaviour: the values and the actions that belong with them.

Class structure

__init__ sets up each new object

__init__ (“dunder init”) is the set-up method: it runs automatically when an object is created. self is this particular object, and an attribute is a value stored on it with a dot (self.name). The attributes set this way belong to that object alone.

class Student: def __init__(self, sid, name): self.sid = sid self.name = name self.grades = [] s = Student("2024-001", "Ana") s.name # "Ana"
  • class Student:start a blueprint called Student (class names start with a capital letter by convention)
  • def __init__(self, sid, name):the set-up method; sid and name are the two inputs to be supplied
  • self.sid = sidstore the input on this object as an attribute called sid (same for name)
  • self.grades = []every new student starts with their own empty list of grades
  • s = Student("2024-001", "Ana")make one object; Python runs __init__ with self = the new student
  • s.nameread an attribute with a dot: "Ana" is the name stored on s
Methods

A method is a function that uses self

A method is a function written inside a class. Its first parameter is self, so it can reach the object’s own attributes. Because the grades live on the object, the object can compute its own average. The data does not need to be passed in again.

class Student: # ...__init__ as before... def average(self): return sum(self.grades) / len(self.grades) s.grades = [88, 92, 79] s.average() # 86.33
  • # ...__init__ as before...the set-up code from the previous slide is still present; it is not repeated here
  • def average(self):a method: no extra inputs, only self — the student it is asked about
  • sum(self.grades) / len(self.grades)add this student’s grades and divide by how many there are
  • s.average()call the method with a dot and ( ); 86.33 is Ana’s mean, 259 ÷ 3 = 86.333… shown rounded
Conceptual model

One class, many objects

class Student the blueprint Ana · [88, 92, 79] avg 86.33 Ben · [70, 75] avg 72.5 Cy · [95, 91, 100] avg 95.33 Each object carries its own data.
Object creation

__init__ runs when an object is created

It is not a constructor in the C++ sense (readers unfamiliar with C++ can ignore this: __init__ is ordinary Python). It is a plain method that Python calls automatically, with the new object as self.

Making an object is filling in a new form. Sale("kape", 15, 3) hands Python three answers, and __init__ copies each one onto the new form, which it calls self.

class Sale: def __init__(self, item, price, qty): self.item = item # attach to THIS object self.price = price self.qty = qty s = Sale("kape", 15, 3) print(s.item, s.price) # kape 15
  • self.item = itemcopy the input item onto this new object (“attach to THIS object”)
  • s = Sale("kape", 15, 3)create one Sale: kape (coffee), price 15, quantity 3
  • print(s.item, s.price)print two attributes; kape 15 is the two values with a space between them

self is the first argument

It is never passed explicitly. Sale("kape", 15, 3) becomes __init__(s, "kape", 15, 3) behind the scenes.

Attributes and methods

Attributes hold data; methods perform actions

An attribute is data the object carries. A method is a function that can reach that data through self.

An attribute is a noun — what the sale has (a price). A method is a verb — what the sale can do (work out its total).

class Sale: def __init__(self, item, price, qty): self.item, self.price, self.qty = item, price, qty def total(self): # a method return self.price * self.qty s = Sale("kape", 15, 3) print(s.price) # attribute — no () # 15 print(s.total()) # method — needs () # 45
  • self.item, self.price, self.qty = item, price, qtyset three attributes in one line: each name on the left gets the value in the same place on the right
  • def total(self):a method that works out price × quantity for this sale
  • s.pricean attribute is stored data, so no brackets: 15
  • s.total()a method is an action, so it needs ( ) to run: 15 × 3 = 45
Default representation

The default printed form of an object

When a custom object is printed, Python shows its type and memory address, which is uninformative in a loop or a debugger.

Key terms

memory address
where the object happens to sit in the computer’s memory (0x103400e00); it says nothing about the data
debugger
a tool that pauses a program so its values can be inspected (covered in a later week)
__repr__
a special method that returns the text Python shows for an object
__str__
its sibling: print() prefers it when a class has both (the lab uses it)
f-string
text with f before the quote; each {name} inside is replaced by its value: f"{2+3} cups" → '5 cups'
print(s) <__main__.Sale object at 0x103400e00> # add one method: def __repr__(self): return f"Sale({self.item!r}, {self.price}, {self.qty})" print(s) Sale('kape', 15, 3)
  • <__main__.Sale object at 0x…>the default: a Sale object from the main program, at some memory address
  • def __repr__(self):indented, so it goes inside class Sale; Python calls it whenever it has to show the object
  • {self.item!r}fill in the item; !r shows it as it would be typed, in quotes: 'kape'
  • Sale('kape', 15, 3)now printing shows what is inside the object

Effect on lists

print([s1, s2]) now shows both sales instead of two addresses, which is where it is most useful.

Dataclasses

@dataclass writes the boilerplate

If a class mainly holds a few fields, Python can generate __init__, __repr__ and == automatically.

Key terms

boilerplate
set-up code written the same way every time
decorator
a line starting with @ directly above a class or function; it adds features to what is below
dataclass
a class whose __init__, __repr__ and == Python writes automatically
field
one attribute listed in a dataclass, with the type it should hold
from dataclasses import dataclass @dataclass class Sale: item: str price: int qty: int def total(self): return self.price * self.qty print(Sale("kape", 15, 3)) Sale(item='kape', price=15, qty=3) print(Sale("kape",15,3) == Sale("kape",15,3)) True
  • from dataclasses import dataclassbring the dataclass tool in from Python’s built-in dataclasses module
  • @dataclassthe decorator: it rewrites the class below, adding set-up, printing and comparing
  • item: stra field called item that should hold a string (a hint: Python does not check it)
  • Sale(item='kape', price=15, qty=3)the automatic __repr__: every field with its value
  • True== now compares the fields, so two sales with equal fields count as equal

Automatic equality

Two plain objects with identical fields are not equal by default — Python compares identity. A dataclass compares the fields.

Exercise · 8 min

Writing a Sale class

Build the class from scratch in a notebook: three fields, one method, one repr.

Key terms

field
one of the attributes listed in a dataclass (item, price, qty)
repr
the printed form of an object, from __repr__ (two slides back)
comprehension
a one-line loop that builds a result, e.g. [x * 2 for x in [1, 2, 3]] gives [2, 4, 6]

Exercise

  1. Make a Sale dataclass with item, price, qty.
  2. Add total() returning price × qty.
  3. Build three sales in a list; print the list.
  4. Sum every total with a comprehension.

Self-check

A dataclass prints its fields, so the list is readable without a hand-written __repr__.

Reuse

Inheritance: a specialised kind of thing

Inheritance builds a new class on an existing one. A discounted sale is a sale. The subclass overrides only what differs and calls super() for the rest.

Key terms

parent / subclass
the existing class (Sale) and the new one built on it (DiscountedSale)
override
write a method with the same name in the subclass, so it replaces the parent’s version
super()
“the parent class”: use it to run the parent’s version of a method
composition
the alternative: store one object as an attribute of another, instead of inheriting

Inheritance is a recipe variation; “chocolate cake” starts from the plain cake recipe and only changes the flavour. It passes the is-a test: a chocolate cake is a cake.

class DiscountedSale(Sale): def __init__(self, item, price, qty, pct): super().__init__(item, price, qty) self.pct = pct def total(self): return round(super().total() * (1 - self.pct/100)) print(Sale("kape", 15, 4)) Sale('kape', total=60) print(DiscountedSale("kape", 15, 4, 25)) DiscountedSale('kape', total=45)
  • class DiscountedSale(Sale):a new class built on Sale (the parent goes in the brackets); it gets all of Sale’s methods
  • super().__init__(item, price, qty)let the parent’s set-up store the three usual attributes…
  • self.pct = pct…then add the one extra attribute that only a discounted sale has
  • def total(self):override: this total replaces the parent’s for discounted sales
  • super().total() * (1 - self.pct/100)the parent’s total (15 × 4 = 60) with 25% off = 45
  • Sale('kape', total=60)printed by a __repr__ on Sale (not shown) that writes the class name and total()

Guideline: use it sparingly

Deep hierarchies are hard to follow. If the child does not pass an is-a test, composition (holding the object) is preferable.

Common error 1

A class attribute is shared by every object

A mutable value placed on the class makes all instances refer to the same list, so adding to one cart changes another.

Key terms

mutable
can be changed in place after it is made: lists, dicts and sets are; numbers and strings are not
class attribute
a value written directly under class: one copy, shared by every object
instance attribute
a value set on self in __init__: each object gets its own
class Cart: items = [] # ONE list for everyone def add(self, x): self.items.append(x) a, b = Cart(), Cart() a.add("kape") print(a.items, b.items) ['kape'] ['kape'] # b was never touched # fix: give each object its own def __init__(self): self.items = [] ['kape'] []
  • items = []directly under class: made once, shared by every Cart
  • self.items.append(x)the object has no list of its own, so this adds to the shared one
  • ['kape'] ['kape']a and b print the same list: b “has” kape although it was only added to a
  • def __init__(self): self.items = []the fix: each new Cart gets its own empty list, so b stays []

Diagnosis

Assignments directly under class run once, when the class is defined. Assignments in __init__ run per object.

Common error 2

A default argument is evaluated only once

The empty list in the signature is created when the def line runs — not on each call. It then persists between calls.

Key terms

signature
the def line: the function’s name and its parameters
default argument
a value a parameter uses when the caller gives none (week 2): basket=[]
None
Python’s value for “nothing here”; test for it with is None
def add_sale(sale, basket=[]): # evaluated ONCE basket.append(sale) return basket print(add_sale("kape")) ['kape'] print(add_sale("load")) ['kape', 'load'] # the old one is still there # the fix, every time def add_sale(sale, basket=None): if basket is None: basket = [] ['kape'] then ['load']
  • basket=[]the [] is made once, when def runs, and reused by every call
  • add_sale("load")the second call gets that same list, still holding kape: ['kape', 'load']
  • if basket is None: basket = []the fix: no basket given → build a fresh list inside, on every call

Rule

A list, dict or set should never be a default. Use None and build the value inside, which runs on every call.

Break — 10 minutes

Next: errors and how Python reports them.

Part B

Errors & exceptions

Real data violates assumptions, so code must anticipate this.

Week 1 introduced the traceback and week 2 introduced if checks. This part covers reading an error systematically, catching expected errors and raising new ones.

Reading an error

Errors as diagnostic messages

When Python cannot continue, it raises an exception — a report of what went wrong — and prints a traceback, the error printout. The last line names the problem; it is read bottom-up.

An exception is a smoke alarm whose label (IndexError, ValueError) indicates which room to check.

nums = [10, 20] nums[5] IndexError: list index out of range int("ninety") ValueError: invalid literal for int()
  • IndexError: list index out of rangeread it as type: message. IndexError = asked for a position that does not exist; nums only has positions 0 and 1
  • ValueError: invalid literal for int()ValueError = the right type (text) but a value int() cannot turn into a whole number
Reading an error

A traceback is read bottom-up

Traceback (most recent call last): File "sales.py", line 8, in <module> print(total(rows)) File "sales.py", line 5, in total return sum(load_price(r) for r ...) File "sales.py", line 2, in load_price return int(row["price"]) ValueError: invalid literal for int() with base 10: 'n/a'

Start at the bottom

The last line states what failed. The lines above are the route Python took to get there, newest call last.

Here, load_price received the string "n/a". The bug is on line 2.

  • Traceback (most recent call last):the heading: the calls (functions running because another line asked) are listed oldest first, newest last
  • File "sales.py", line 8, in <module>where it started: line 8 of sales.py, at the top level of the file (<module>)
  • File "sales.py", line 2, in load_pricethe deepest call: line 2, inside the function load_price — check this line first
  • ValueError: … 'n/a'the error type and the bad value: the text 'n/a' cannot become a whole number (base 10 = ordinary digits)
Common exceptions

Seven exceptions and their actual messages

ExceptionWhat Python saidUsually means
ValueErrorinvalid literal for int() with base 10: 'n/a'Right type, impossible value
TypeErrorcan only concatenate str (not "int") to strWrong type entirely (joining, or “concatenating”, text with a number)
KeyError'price'That key is not in the dict
IndexErrorlist index out of rangePast the end of the list
FileNotFoundError[Errno 2] No such file or directoryWrong path, or wrong working dir (the folder Python is running in)
ZeroDivisionErrordivision by zeroAveraging an empty group
AttributeError'str' object has no attribute 'push'Wrong method for that type

The exception name is the diagnosis and the message is the symptom. KeyError: 'price' means that the key price was looked up and not found.

Handling exceptions

try and except for lines that may fail

The line that might fail is wrapped in a try block. If it raises the named exception, the except block runs instead of crashing.

try/except is a safety net under one act; if the act fails in the expected way, the program continues.

raw = input("Score: ") # user types "ninety" try: score = int(raw) except ValueError: print("Not a number — using 0") score = 0
  • raw = input("Score: ")input() shows the prompt and waits for typing; it always gives back text. Here the user typed "ninety"
  • try:attempt the indented line(s) below
  • score = int(raw)the risky line: int("ninety") raises a ValueError
  • except ValueError:if exactly that error happens, jump here instead of crashing
  • score = 0the fallback (a sensible replacement): the program carries on with 0
All four blocks

The roles of else and finally

Beyond try/except, the other two blocks state when code runs, which prevents bugs: else runs only when nothing went wrong, finally runs every time.

try: n = int(v) except ValueError: print(f"{v!r} is not a number") else: print(f"parsed {n}") # only if nothing raised finally: print("runs either way") # parse("15") parsed 15 runs either way # parse("n/a") 'n/a' is not a number runs either way
  • # parse("15")these lines are assumed to be inside a function parse(v); v is the text to convert
  • else:good input: try worked, so else prints parsed 15
  • finally:runs in both cases — the place for clean-up
  • {v!r}bad input: except runs, and !r keeps the quotes, showing that it was text

Purpose of else

Exceptions from extra code placed in try are caught unintentionally. else keeps the guarded part limited to the risky line.

Common error

A bare except hides the cause of an error

A bare except is except: with no error name. It catches everything, including typos in the code and Ctrl-C (the keys that stop a running program). The result is "something went wrong", with no way to find the cause.

# never do this try: n = int(v) except: print("something went wrong") something went wrong # do this — name what you expect except ValueError as e: print(f"bad number: {e}") bad number: invalid literal for int()… 'n/a'
  • except:nothing after it: catches every error, even a misspelled variable name
  • something went wrongthe output says nothing about what or where
  • except ValueError as e:catch only ValueError, and give the caught error the name e
  • {e}printing e shows Python’s own message, so the bad value 'n/a' is still visible

Guideline: catch narrowly

An unpredicted exception should stop the program during development. Silencing it moves the failure somewhere harder to find.

Common exceptions

Six exceptions worth recognising

ExceptionHappens whenExample
ValueErrorright type, wrong valueint("abc")
KeyErrordict key missingpop["Manila"]
IndexErrorlist position too bignums[99]
FileNotFoundErrorfile does not existopen("nope.txt")
ZeroDivisionErrordividing by zerototal / 0
TypeErrorwrong type entirely"a" + 1
Raising errors

Raising an error on bad input

An invalid value should not pass to later steps. It is checked on entry; if invalid, the function executes raise with a ValueError and a message stating what went wrong. To raise is to stop deliberately and report an exception.

def set_grade(g): if not 0 <= g <= 100: raise ValueError(f"out of range: {g}") return g set_grade(130) ValueError: out of range: 130
  • if not 0 <= g <= 100:“if g is not between 0 and 100” — Python allows chained comparisons like in maths
  • raise ValueError(f"out of range: {g}")stop here and report a ValueError with our own message
  • return gonly reached when the grade is fine
  • ValueError: out of range: 130the last line of the traceback (only that line is shown): the type, then our message
Custom exceptions

Custom exceptions for domain-specific errors

A custom exception is a user-defined error type: a class that inherits from the closest built-in exception. Callers can then catch this specific failure, or fall back to the general one.

class PriceError(ValueError): """Raised when a price cannot be trusted.""" def check(p): if p < 0: raise PriceError(f"price cannot be negative: {p}") return p try: check(-5) except PriceError as e: print(e) price cannot be negative: -5
  • class PriceError(ValueError):a new kind of error, built on ValueError — Part A’s inheritance, used for errors
  • """Raised when…"""a docstring: the class’s one-line description; the class needs no other code
  • raise PriceError(f"…{p}")raise the custom type, with a message that includes the bad price
  • except PriceError as e: print(e)catch it by name; printing e gives price cannot be negative: -5

Inherit deliberately

Because PriceError subclasses ValueError, code that only knows about ValueError still works.

Cleanup

with closes resources even after an error

A context manager is any object usable with with: it guarantees that cleanup runs, without finally or a manual .close().

with is a library book with automatic return; on leaving the indented block the book is returned, even if an error occurred.

with open("sales.csv") as f: rows = f.readlines() # file is closed here, even if readlines() raised print(f.closed) True
  • with open("sales.csv") as f:open the file and call it f for the indented block; with promises to close it afterwards
  • rows = f.readlines()read every line of the file into a list (week 3)
  • print(f.closed)outside the block: True means the file is already closed

Later use

Database connections, locks, timers and matplotlib figures all use the same pattern.

Guideline

Handling recoverable errors and surfacing the rest

Exercise · 6 min

Triggering errors and reading the messages

Errors are easier to learn by causing them. Run each line, and name the exception before reading the output.

Exercise

  1. int("12.5")
  2. [1,2,3][3]
  3. {"a":1}["b"]
  4. open("nope.csv")

Self-check

ValueError · IndexError · KeyError · FileNotFoundError. The last one names the file it could not find: check the spelling, and the working directory (the folder Python is running in).

Review question

Question (select to reveal the answer)

A script stops with KeyError: 'price'. Where should the search start?

A · The top line of the traceback
B · The bottom line, then the deepest file shown
C · The middle of the traceback
D · Rerun without changes

B — bottom-up.

The final line names the failure; the file directly above it is where the bad code lives. The top of a traceback is only where the program started.

Review question

Question (select to reveal the answer)

Reading ages["Rizal"] from a dict that has no "Rizal" key raises which exception?

A · ValueError
B · IndexError
C · KeyError
D · TypeError

C — KeyError.

Missing keys raise KeyError; missing list positions raise IndexError. .get() is appropriate when a gap is expected.

Break

  Five minutes

Next: organising this code across files.

Part C

Organizing code

From one long notebook to files that import each other.

Parts A and B covered functions and classes in one notebook. This part moves them into files (modules) that any notebook can import.

Modules

Moving reusable code into a .py file

A module is a .py file of Python code. With the functions in grades.py, any notebook or script can import them (bring them in by name): one definition, used everywhere, fixed in one place.

A module is a recipe card in a shared binder; every cook (notebook) uses the same card, so one correction fixes it for everyone.

# grades.py def average(scores): return sum(scores) / len(scores) # analysis.ipynb from grades import average average([88, 92]) # 90.0
  • # grades.pya plain file called grades.py, saved in the same folder as the notebook: this is the module
  • # analysis.ipynbthe Jupyter notebook (.ipynb) used for the analysis
  • from grades import averagefind grades.py and bring the name average into this notebook
  • average([88, 92])works as if written here; 90.0 is a float because / always gives a decimal
Import forms

Three import forms and when to use each

FormCall syntaxUse when
import gradesgrades.average(x)the source should be obvious
from grades import averageaverage(x)one name is used often
import numpy as npnp.mean(x)the community's standard alias
Imports

Trade-offs of the three import forms

All three work. Most code uses the second, because the reader can see where a name came from.

# 1 — clear, slightly verbose import sales sales.total(rows) # 2 — the usual choice from sales import total total(rows) # 3 — avoid: where did `total` come from? from sales import *

Problem with star imports

It can silently overwrite an existing name, and a reader cannot tell which module a function belongs to.

The main guard

Purpose of if __name__ == "__main__"

A file has two uses: it can be run, and it can be imported. This line separates them.

Key term

__name__
a variable Python fills in for every file: "__main__" when that file is run directly, its own name ("sales") when another file imports it

A file can be run like a program or borrowed like a toolbox. The guard marks the lines that should happen only when it is run as a program.

# sales.py def total(rows): ... if __name__ == "__main__": # only when you run `python sales.py` print(total(load("sales.csv"))) # elsewhere: from sales import total # does NOT run the print
  • def total(rows): ...the ... means “body left out to save space”
  • if __name__ == "__main__":true only when this file is run directly with python sales.py
  • from sales import totalimporting sets __name__ to "sales", so the indented print is skipped

Without it

Importing the module would execute its test code, read files and print output every time, from anywhere.

Project layout

A project layout that others can navigate

Separate raw data, code, and notebooks. A README says what the project is; requirements.txt lists what to install.

Key terms

folder / directory
two names for the same thing; data/ ends in / to show it is a folder
README.md
a text file explaining the project, the first thing a visitor reads (.md = Markdown, plain text with simple formatting)
requirements.txt
the list of libraries to install, one per line, e.g. pandas
project/ data/ # raw + processed src/ grades.py # reusable code notebooks/ analysis.ipynb README.md requirements.txt
Layout

A complete project layout

sari_project/ data/ raw/ # never edited by hand processed/ # written by your code src/ __init__.py load.py # reading files/APIs clean.py # one job per module analyse.py notebooks/ 01-explore.ipynb tests/ README.md requirements.txt

Raw data is read-only

A wrong cleaning step can be rerun. A hand edit to the raw file cannot be undone.

Notebooks for exploration, modules for logic

Anything needed twice moves into src/. A notebook is for exploration, not for core logic.

README first

What the project is and how to run it. It is best written on the first day.

Key terms

package
src/ is a package: a folder of modules. The (often empty) __init__.py file tells Python it may import from it
tests/
code that checks that the project code still gives the right answers
API
a way for code to request data from a website or program (a later week)
Script or import

The __main__ guard

Code under if __name__ == "__main__": runs only when the file is launched directly, not when another file imports it. Importing therefore never triggers side effects.

# grades.py def main(): print("run directly") if __name__ == "__main__": main()
  • def main():a function holding what the script should do when run
  • if __name__ == "__main__":call main() only when grades.py is run directly; importing it runs nothing
Review question

Question (select to reveal the answer)

After from stats import mean, how is it called?

A · stats.mean(x)
B · mean(x)
C · import mean(x)
D · stats(mean, x)

B — mean(x).

The from ... import name form brings the name in directly, so it is used without a prefix. stats.mean(x) is needed only after a plain import stats.

This week's lab

Building, guarding and separating a class

The lab covers writing a small Student class, add methods, make it print readably, build a subclass, catch a bad value with try/except, and raise a clear error on a bad grade. ~45 minutes, all in the browser.

Lab tasks

__init__, self, methods, __str__, inheritance, try/except/finally, raise, and a custom exception.

Optional extension

Move the Student class into student.py in a real notebook and import it back.

Summary

Bundling, guarding and organising code

Summary

Four main points

1 · A class bundles data with behaviour

Attributes hold, methods do, __init__ sets up. Add __repr__ or use @dataclass so it prints.

2 · Read tracebacks bottom-up

Last line = what failed. The file above it = where. This alone resolves most bugs this term.

3 · Catch narrowly, never bare

Name the expected exception. Unpredicted ones should stop the program, where they can still be found.

4 · Reusable code leaves the notebook

Into a module, behind if __name__ == "__main__", in a layout that others can navigate.

Glossary

Week 4 terms

Part A · Classes

class
a blueprint for one kind of thing: what it holds and does
object / instance
one thing built from a class — one cookie from the cutter
attribute
a value stored on an object: ana.name, no brackets
method
a function inside a class, called with brackets: ana.average()
self
inside a class, “this particular object”
__init__
set-up method Python runs automatically when an object is made
__repr__ / __str__
methods that give the text shown when an object is printed
f-string
f"…" text where each {name} is replaced by its value
@dataclass
decorator that writes __init__, __repr__ and == automatically
inheritance
building a subclass on a parent class; it gets all the parent’s methods
override / super()
replace a parent’s method / call the parent’s version
mutable
can be changed in place: lists, dicts, sets
comprehension
a one-line loop that builds a result: [x * 2 for x in nums]

Parts B & C · Errors and files

exception
Python’s report that something went wrong; stops the program unless handled
traceback
the error printout; read the last line first, then its line number
try / except
attempt risky code; run the except block if that named error happens
else / finally
else: only when no error; finally: always, for clean-up
bare except
except: with no name — catches everything, hides bugs
raise
stop deliberately and report an exception with a custom message
custom exception
a user-defined error class, built on a built-in one like ValueError
with
opens something and guarantees it is closed afterwards
module
a .py file whose code other files import
import / alias
bring names in from a module / a nickname given with as
package
a folder of modules, marked by an __init__.py file
__main__ guard
if __name__ == "__main__": — runs only when the file is run directly
README / requirements.txt
what the project is / which libraries to install
Preparation for next week

Practice & reading

Next Week

Scientific computing with NumPy

Arrays that apply maths to thousands of numbers at once, faster and shorter than an equivalent hand-written loop.

DS 208 · Programming for Data Science