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
Bundle data and the behaviour that belongs with it into one object.
Anticipating bad input: catching errors that can be handled and letting real bugs surface.
Splitting code across files and importing it, so that projects stay navigable.
So far all code has been in one place. Real projects consist of many files that depend on each other; this week shows how.
Write a class, handle an error deliberately, and import a self-written module.
Week 3 covered lists, dictionaries and reading files, which fill a notebook quickly. Structure prevents it from becoming a long sequence of tangled cells.
Copy-pasted logic and very long cells become difficult to fix or trust.
Group related data and behaviour, guard against bad input, and split into files.
Ole-Johan Dahl and Kristen Nygaard introduce objects, classes and inheritance.
Python’s first public release already has classes and exception handling.
Dahl and Nygaard receive computing’s highest prize for the idea.
The creators of C++ and Java both name Simula as a major influence; Python’s classes follow the same idea.
A class is a template; an object is one thing made from it, as one house is built from one blueprint.
All data in Python is an object: isinstance(5, object) is True.
pandas’ table is a class, so df.head() is a method call.
ValueError and every other exception is a class.
This week’s classes explain the dot in df.head() and text.lower(), used in every later week.
obj.method()SourcePython Language Reference, §3.1 Objects, values and types; Built-in Exceptions
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
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
A value stored on an object. It is read with a dot and no brackets.
e.g. ana.name gives 'Ana'
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
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
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__
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
Python’s report that something went wrong while running. It stops the program unless the code handles it.
e.g. ValueError, KeyError, IndexError
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 a risky line; if a named exception happens, run the except block instead of crashing.
e.g. try: int(raw) … except ValueError: score = 0
Stop deliberately and report an exception, with a custom message.
e.g. raise ValueError("out of range: 130")
A .py file of code that other files can import (bring in) and reuse.
e.g. grades.py, then from grades import average
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
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.
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.
Groups behaviour: inputs in, output out.
Groups data + behaviour: the values and the actions that belong with them.
__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: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 suppliedself.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 gradess = Student("2024-001", "Ana")make one object; Python runs __init__ with self = the new students.nameread an attribute with a dot: "Ana" is the name stored on sselfA 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.
# ...__init__ as before...the set-up code from the previous slide is still present; it is not repeated heredef average(self):a method: no extra inputs, only self — the student it is asked aboutsum(self.grades) / len(self.grades)add this student’s grades and divide by how many there ares.average()call the method with a dot and ( ); 86.33 is Ana’s mean, 259 ÷ 3 = 86.333… shown roundedThe class is written once. Every Student(...) call makes a fresh
object with independent attributes.
Student is written once; Ana, Ben and Cy are three separate objects, so changing Ben’s grades never touches Ana’s.
A pandas DataFrame (the code-controlled table of week 6) is an object too — data plus methods like
.mean().
__init__ runs when an object is createdIt 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.
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 3print(s.item, s.price)print two attributes; kape 15 is the two values with a space between themself is the first argumentIt is never passed explicitly. Sale("kape", 15, 3) becomes __init__(s, "kape", 15, 3) behind the scenes.
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).
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 rightdef total(self):a method that works out price × quantity for this sales.pricean attribute is stored data, so no brackets: 15s.total()a method is an action, so it needs ( ) to run: 15 × 3 = 45When a custom object is printed, Python shows its type and memory address, which is uninformative in a loop or a debugger.
0x103400e00); it says nothing about the dataprint() prefers it when a class has both (the lab uses it)f before the quote; each {name} inside is replaced by its value: f"{2+3} cups" → '5 cups'<__main__.Sale object at 0x…>the default: a Sale object from the main program, at some memory addressdef __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 objectprint([s1, s2]) now shows both sales instead of two addresses, which is where it is most useful.
@dataclass writes the boilerplateIf a class mainly holds a few fields, Python can generate __init__, __repr__ and == automatically.
@ directly above a class or function; it adds features to what is below__init__, __repr__ and == Python writes automaticallyfrom 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 comparingitem: 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 valueTrue== now compares the fields, so two sales with equal fields count as equalTwo plain objects with identical fields are not equal by default — Python compares identity. A dataclass compares the fields.
Build the class from scratch in a notebook: three fields, one method, one repr.
item, price, qty)__repr__ (two slides back)[x * 2 for x in [1, 2, 3]] gives [2, 4, 6]Sale dataclass with item, price, qty.total() returning price × qty.A dataclass prints its fields, so the list is readable without a hand-written __repr__.
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.
Sale) and the new one built on it (DiscountedSale)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):a new class built on Sale (the parent goes in the brackets); it gets all of Sale’s methodssuper().__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 hasdef total(self):override: this total replaces the parent’s for discounted salessuper().total() * (1 - self.pct/100)the parent’s total (15 × 4 = 60) with 25% off = 45Sale('kape', total=60)printed by a __repr__ on Sale (not shown) that writes the class name and total()Deep hierarchies are hard to follow. If the child does not pass an is-a test, composition (holding the object) is preferable.
A mutable value placed on the class makes all instances refer to the same list, so adding to one cart changes another.
class: one copy, shared by every objectself in __init__: each object gets its ownitems = []directly under class: made once, shared by every Cartself.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 adef __init__(self): self.items = []the fix: each new Cart gets its own empty list, so b stays []Assignments directly under class run once, when the class is defined. Assignments in __init__ run per object.
The empty list in the signature is created when the def line runs — not on each call. It then persists between calls.
def line: the function’s name and its parametersbasket=[]is Nonebasket=[]the [] is made once, when def runs, and reused by every calladd_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 callA list, dict or set should never be a default. Use None and build the value inside, which runs on every call.
Next: errors and how Python reports them.
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.
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.
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 1ValueError: invalid literal for int()ValueError = the right type (text) but a value int() cannot turn into a whole numberThe 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 lastFile "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 firstValueError: … 'n/a'the error type and the bad value: the text 'n/a' cannot become a whole number (base 10 = ordinary digits)| Exception | What Python said | Usually means |
|---|---|---|
ValueError | invalid literal for int() with base 10: 'n/a' | Right type, impossible value |
TypeError | can only concatenate str (not "int") to str | Wrong type entirely (joining, or “concatenating”, text with a number) |
KeyError | 'price' | That key is not in the dict |
IndexError | list index out of range | Past the end of the list |
FileNotFoundError | [Errno 2] No such file or directory | Wrong path, or wrong working dir (the folder Python is running in) |
ZeroDivisionError | division by zero | Averaging 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.
try and except for lines that may failThe 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: ")input() shows the prompt and waits for typing; it always gives back text. Here the user typed "ninety"try:attempt the indented line(s) belowscore = int(raw)the risky line: int("ninety") raises a ValueErrorexcept ValueError:if exactly that error happens, jump here instead of crashingscore = 0the fallback (a sensible replacement): the program carries on with 0else and finallyBeyond try/except, the other two blocks state when code runs, which prevents bugs:
else runs only when nothing went wrong, finally runs every time.
# parse("15")these lines are assumed to be inside a function parse(v); v is the text to convertelse:good input: try worked, so else prints parsed 15finally:runs in both cases — the place for clean-up{v!r}bad input: except runs, and !r keeps the quotes, showing that it was textelseExceptions from extra code placed in try are caught unintentionally. else keeps the guarded part limited to the risky line.
except hides the cause of an errorA 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.
except:nothing after it: catches every error, even a misspelled variable namesomething went wrongthe output says nothing about what or whereexcept 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 visibleAn unpredicted exception should stop the program during development. Silencing it moves the failure somewhere harder to find.
| Exception | Happens when | Example |
|---|---|---|
ValueError | right type, wrong value | int("abc") |
KeyError | dict key missing | pop["Manila"] |
IndexError | list position too big | nums[99] |
FileNotFoundError | file does not exist | open("nope.txt") |
ZeroDivisionError | dividing by zero | total / 0 |
TypeError | wrong type entirely | "a" + 1 |
The specific expected exception is named after except. Catching the exact exception lets real
bugs still surface.
Match the exception to the failure; avoid a blanket catch-all.
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.
if not 0 <= g <= 100:“if g is not between 0 and 100” — Python allows chained comparisons like in mathsraise ValueError(f"out of range: {g}")stop here and report a ValueError with our own messagereturn gonly reached when the grade is fineValueError: out of range: 130the last line of the traceback (only that line is shown): the type, then our messageA 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):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 coderaise PriceError(f"…{p}")raise the custom type, with a message that includes the bad priceexcept PriceError as e: print(e)catch it by name; printing e gives price cannot be negative: -5Because PriceError subclasses ValueError, code that only knows about ValueError still works.
with closes resources even after an errorA 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:open the file and call it f for the indented block; with promises to close it afterwardsrows = 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 closedDatabase connections, locks, timers and matplotlib figures all use the same pattern.
A sensible fallback (a replacement plan) exists: skip a bad row, use a default, retry.
It signals a bug in the program’s own logic. Hiding it only delays the problem.
A bare except: that catches everything, including typos.
As in DS 227, the default is a choice. Skipping, defaulting or flagging a bad value is a deliberate decision.
Catch narrowly, handle transparently, and log (keep a written note of) what was skipped.
Errors are easier to learn by causing them. Run each line, and name the exception before reading the output.
int("12.5")[1,2,3][3]{"a":1}["b"]open("nope.csv")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).
A script stops with KeyError: 'price'. Where should the search start?
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.
Reading ages["Rizal"] from a dict
that has no "Rizal" key raises which exception?
ValueErrorIndexErrorKeyErrorTypeErrorC — KeyError.
Missing keys raise
KeyError; missing list positions raise IndexError.
.get() is appropriate when a gap is expected.
Keys and indexes are frequently confused. The container type determines the error.
Dict → KeyError. List → IndexError.
Next: organising this code across files.
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.
.py fileA 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.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 analysisfrom grades import averagefind grades.py and bring the name average into this notebookaverage([88, 92])works as if written here; 90.0 is a float because / always gives a decimal| Form | Call syntax | Use when |
|---|---|---|
import grades | grades.average(x) | the source should be obvious |
from grades import average | average(x) | one name is used often |
import numpy as np | np.mean(x) | the community's standard alias |
An alias is a short nickname chosen with as.
Aliases such as np and pd are widely recognised conventions and
should be kept.
from grades import * (* = “everything”) — it hides where names came from.
All three work. Most code uses the second, because the reader can see where a name came from.
It can silently overwrite an existing name, and a reader cannot tell which module a function belongs to.
if __name__ == "__main__"A file has two uses: it can be run, and it can be imported. This line separates them.
"__main__" when that file is run directly, its own name ("sales") when another file imports itA 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.
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.pyfrom sales import totalimporting sets __name__ to "sales", so the indented print is skippedImporting the module would execute its test code, read files and print output every time, from anywhere.
Separate raw data, code, and notebooks. A README says what the
project is; requirements.txt lists what to install.
data/ ends in / to show it is a folder.md = Markdown, plain text with simple formatting)pandasA wrong cleaning step can be rerun. A hand edit to the raw file cannot be undone.
Anything needed twice moves into src/. A notebook
is for exploration, not for core logic.
What the project is and how to run it. It is best written on the first day.
src/ is a package: a folder of modules. The (often empty) __init__.py file tells Python it may import from it__main__ guardCode under if __name__ == "__main__": runs only when the file is
launched directly, not when another file imports it. Importing therefore never triggers side
effects.
def main():a function holding what the script should do when runif __name__ == "__main__":call main() only when grades.py is run directly; importing it runs nothingAfter from stats import mean, how is
it called?
stats.mean(x)mean(x)import mean(x)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.
The import form determines the call form.
from m import f → call f() bare.
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.
__init__, self, methods, __str__, inheritance,
try/except/finally, raise, and a custom exception.
Move the Student class into student.py in a real notebook and import it back.
Data + behaviour in one object. __init__ builds it; self is
the current object.
Catch the specific expected exception; raise on bad input; never
catch everything.
Reusable code in modules, imported cleanly, in a layout others can read.
Summary: group what belongs together, anticipate what can go wrong, and give every piece a defined location.
Structure a project instead of placing all code in one cell.
Attributes hold, methods do, __init__ sets up. Add
__repr__ or use @dataclass so it prints.
Last line = what failed. The file above it = where. This alone resolves most bugs this term.
Name the expected exception. Unpredicted ones should stop the program, where they can still be found.
Into a module, behind if __name__ == "__main__", in
a layout that others can navigate.
ana.name, no bracketsana.average()f"…" text where each {name} is replaced by its value__init__, __repr__ and == automatically[x * 2 for x in nums]else: only when no error; finally: always, for clean-upexcept: with no name — catches everything, hides bugs.py file whose code other files importas__init__.py fileif __name__ == "__main__": — runs only when the file is run directlyFinish the Week 4 lab and submit it. Be able to write a class and a
try/except from memory.
Python Tutorial §8 (errors and exceptions) and §9.1–9.4 (classes) —
docs.python.org/3/tutorial.
Everything here is linked on the course page beside this deck.
Whole-array maths with NumPy replaces explicit loops.
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