Skip to main content

Practice 7 — Structured and conditional data

Skills: 6​

Reading: the Notes sections of Class 19 and Class 20​

Structured Data​

Many pieces of real-world information consist of several parts that should be kept together. Structured data bundles multiple fields into a single value.

Defining a Structured Data Type​

Define a new data type called Student to represent a student:

from dataclasses import dataclass

@dataclass
class Student:
name: str
id: int
gpa: float

Creating Examples​

Create instances of Student using the constructor Student:

alice = Student("Alice Smith", 12345, 3.7)
bob = Student("Bob Martinez", 23456, 3.2)
carol = Student("Carol Johnson", 34567, 3.9)

What do you expect to happen if you try to create a student with a string for the ID number?

Extracting Fields​

Design a function student_info that returns a formatted string for a student:

What is the result of student_info(alice)?

Writing Functions with Structured Data​

Design a function honors_student that returns True if a student has a GPA of 3.5 or higher:

Conditional Data​

Sometimes data can come in multiple forms and we need a way to represent alternatives within one type. Conditional data can be one of several variants.

Defining a Conditional Data Type​

Define a new type called OrderType with three variants:

@dataclass
class Pickup:
pass

@dataclass
class Delivery:
address: str
tip: float

@dataclass
class Curbside:
car_color: str
license_plate: str

OrderType = Pickup | Delivery | Curbside

How many different ways can someone receive their order according to our OrderType?

Creating Examples​

Create instances of OrderType:

order_1 = Pickup()
order_2 = Delivery("360 Huntington Ave, Boston MA", 5.00)
order_3 = Curbside("red", "ABC123")

Taking Apart Variants with match​

Design a function order_instructions that returns instructions for fulfilling an order:

def order_instructions(o: OrderType) -> str:
match o:
case Pickup():
pass # YOUR CODE HERE
case Delivery(addr, tip_amount):
pass # YOUR CODE HERE
case Curbside(color, plate):
pass # YOUR CODE HERE

def test_order_instructions():
assert order_instructions(Pickup()) == "Order ready for pickup at counter"
assert order_instructions(order_3) == "Look for red car with plate ABC123 in parking lot"

Processing Fields in Variants​

Design a function total_cost that calculates the total cost including any service fees:

What information do we use and ignore in each case?

Wrap-Up​

When would you use structured data instead of separate variables? Why is pattern matching with match better than using if-statements for conditional data?