──────────────────────────────────────

26. Equipment Checkout · Define the Shape of a Record

Use a dataclass for a record with named attributes and defaults.

Lesson files · lessons/models-and-state/dataclass-record

Before you start
- Create an instance of a class and read its attributes.
- Recognise a type annotation and a default value.

By the end
- Declare an item name and a quantity with a default of one.
- Create an item from input and print its two stored fields.

Where you can use it
Start a stock list with a required name and a standard quantity for each new record.

Use a dataclass when a class mainly carries data. Python can build the constructor from the fields you declare. Put required fields before defaulted fields. Keep an ordinary dictionary for variable keys or for loose JSON at a boundary.

Predict
Where does the available value come from?
- The word Camera.
- The default on the dataclass field.

Worked example (example.py)

from dataclasses import dataclass

@dataclass
class Item:
    name: str
    available: bool = True

print(Item("Camera").available)


Example result
True

Read a name and use a dataclass with name and quantity fields. Default quantity to 1. Print the name and quantity.

Starter program (starter.py)

from dataclasses import dataclass

@dataclass
class Item:
    name: str
    available: bool = True

print(Item("Camera").available)


Hint
Replace the availability field with quantity: int = 1. Store the created instance before printing its attributes.

Case 1. Try the sample
Input
Tripod
Expected output
Tripod: 1

Case 2. Another item name
Input
Light kit
Expected output
Light kit: 1

Stretch
Create another item and explicitly pass quantity=3.

Reflect
What would you put in a method instead of storing as a field?

Check your prediction
The default on the dataclass field. The constructor uses the field default when the caller omits that argument.
