Skip to content
Tutorials Center
My learning

Topics

Lesson 136 of 149 ยท Projects

Project: Inventory Manager

Build an inventory manager in Python with data classes, custom exceptions, reports, JSON saving and a command-line interface driven by pattern matching.

Every shop, warehouse and workshop needs to know what it has in stock. In this project you'll build an inventory manager for a small hardware store: it tracks items, sells and restocks them, refuses impossible operations with clear errors, prints reports, saves everything to a JSON file and accepts typed commands like sell LMP-01 2.

This is the most "object-oriented" of the projects. You'll use data classes, a regular class with special methods, custom exceptions, JSON, pattern matching and type hints. The program grows in six stages, and every stage is complete and runnable on its own.

The plan

Before writing code, it helps to decide what the pieces are and what each one is responsible for:

Piece Job
Item One product: SKU (stock-keeping unit, a short product code), name, quantity, price, category. Validates itself.
Inventory The collection of items. Adds, finds, sells and restocks; computes totals; saves and loads.
Exceptions InventoryError and its subclasses describe everything that can go wrong.
Command loop Reads text commands, calls the inventory and prints results or errors.

Keeping these responsibilities separate means each part stays small. The Inventory never prints anything and never reads input, so it could later sit behind a web page or an app without changes.

Stage 1: the Item data class

A data class writes __init__, __repr__ and __eq__ for us. We add two things: a __post_init__ method that rejects impossible values, and a value property that computes how much the stock of this item is worth:

Python Stage 1: an Item that validates itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

__post_init__ runs automatically right after the generated __init__, which makes it the natural place for validation. Because invalid items can never be created, the rest of the program can trust every Item it sees.

Stage 2: the Inventory class

The inventory stores items in a dictionary keyed by SKU, so finding an item is instant. A few special methods make it feel like a built-in collection: __len__ makes len(inventory) work, __iter__ makes it loopable, and __contains__ makes "LMP-01" in inventory work:

Python Stage 2: a collection of items

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The attribute is named _items with a leading underscore, the Python convention for "internal; please use the methods instead". Note the default argument items: list[Item] | None = None instead of = [], which avoids the shared mutable default trap.

Try store.get("XYZ"): you get a bare KeyError: 'XYZ'. That's accurate but not very friendly. Let's fix that next.

Stage 3: custom exceptions, selling and restocking

A good library reports problems in its own vocabulary. We define one base class, InventoryError, and specific subclasses. Code that uses the inventory can catch one specific problem, or every inventory problem at once with except InventoryError:

Python Stage 3: sell, restock and clear errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three techniques from the exceptions chapter appear here:

  • Each exception class stores useful data (sku, item, requested) as attributes, so code that catches it can react, for example by offering to sell the available quantity instead.
  • raise ItemNotFoundError(sku) from None replaces the internal KeyError with our own error and hides the original from the traceback, since it's an implementation detail.
  • sell() checks everything before changing anything. A failed sale leaves the stock untouched.

The lambda list in the demo is just a compact way to try several failing calls in one loop; see Lambda Functions.

Stage 4: reports

Raw print(item) output is fine for debugging, but a shop owner wants a table. We add two reporting methods: a sorted listing with a total, and a low-stock warning list. Formatting with fixed-width f-string fields lines the columns up:

Python Stage 4: stock and low-stock reports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

To keep this stage focused on reports, the validation and exceptions are left out; they all come back in the final program. Two details:

  • sorted(self, key=lambda i: (i.category, i.name)) sorts by two keys: first category, then name within a category. Tuples compare element by element, which makes multi-key sorting this easy.
  • report() returns a string instead of printing it. The caller decides whether to print it, save it to a file or send it somewhere else.

Stage 5: saving to JSON

Inventory that disappears when the program ends isn't much use. JSON is a natural format: readable, and understood by every language. dataclasses.asdict() turns an Item into a plain dictionary that json can write, and Item(**data) unpacks a dictionary back into an item:

Python Stage 5: save and load

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

load() is a class method: it's called on the class (Inventory.load(path)) and returns a new instance, a pattern called an alternative constructor. The comparison at the end works because data classes generate __eq__, which compares items field by field.

In this editor, inventory.json lives in a temporary in-memory file system and disappears after the run. On your computer, it would be a real file next to your script.

Money and floats. Prices like 24.90 can't be stored exactly as floats (see Numbers). That's fine for a learning project, but real accounting code uses decimal.Decimal or stores prices as whole cents in an int.

Stage 6: the complete program with commands

The last stage puts everything together and adds a command loop. Each line of input is a command. shlex.split() splits a line like a terminal would, so quoted names with spaces stay together, and a match statement picks the action by the command's shape:

TEXT
add SKU 'Name with spaces' QUANTITY PRICE [CATEGORY]
sell SKU AMOUNT        restock SKU AMOUNT
list                   low
quit

Every error, whether ours or a bad number typed by the user, is caught and printed, and the loop carries on. When the user quits, the inventory is saved. To prove that saving works, the program runs two sessions in a row: the second one starts by loading the file the first one saved.

Python Stage 6: the complete inventory manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read through the output alongside the commands in the Input box. Every bad command produces a helpful message instead of a crash: selling more hammers than exist, adding a duplicate SKU, typing abc as an amount (that's the ValueError from int("abc")) and an unknown command. Session 2 starts by loading the file, and its stock list shows the changes made in session 1.

Points worth noticing:

  • The match patterns describe the command's shape. ["add", sku, name, quantity, price, *rest] only matches an add with at least four more words and captures them by name. [command, *_] catches anything else that isn't empty.
  • Echoing the command with print(f"> {line}") makes the log readable here, because the Input box's lines aren't shown in the output.
  • Item(**asdict(item)) copies the starter items, so changing stock never modifies the STARTER_STOCK constant.
  • The interface catches errors; the model raises them. Inventory never prints, and handle() never checks stock levels itself.

To try your own commands, edit the Input box: for example, add a new product, sell it, then list.

Ideas to extend the manager

  1. A remove command that deletes an item, raising ItemNotFoundError when it doesn't exist.
  2. Sales history. Record each sale (SKU, amount, total, date and time) and add a sales command that prints today's revenue.
  3. Search. A find lamp command that lists items whose names contain the word, ignoring case.
  4. CSV export. Write the report to a CSV file that opens in a spreadsheet.
  5. Tests. Write unit tests for Inventory: selling reduces stock, overselling raises InsufficientStockError and leaves the quantity unchanged, and save followed by load gives equal items.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does the Item data class validate its values?

    __post_init__ runs right after the data class's generated __init__, so an invalid Item can never be created.
  2. 2. Why do all the custom exceptions inherit from InventoryError?

    A common base class lets code handle all inventory errors at once, while still allowing specific subclasses to be caught separately.
  3. 3. What does raise ItemNotFoundError(sku) from None do?

    from None suppresses the exception context, so the user only sees the meaningful ItemNotFoundError.
  4. 4. How does stage 5 turn a JSON record back into an Item?

    **record unpacks the dictionary's keys and values as keyword arguments, matching the data class fields.
  5. 5. Why does the Stage 6 program run two sessions?

    The in-memory file system is cleared after every run, so the program simulates "closing and reopening" by running a second session that loads the saved file.

Summary

  • A data class with __post_init__ validation and a computed @property makes a reliable model object.
  • A container class with __len__, __iter__ and __contains__ behaves like a built-in collection.
  • A hierarchy of custom exceptions with useful attributes reports problems in the program's own vocabulary; check everything before changing state.
  • asdict(), json.dumps() and Item(**data) with a @classmethod loader give simple JSON persistence.
  • A command loop with shlex.split() and match turns text into actions, catching errors so one bad command never crashes the program.

Next: Project: Data Report, where you'll turn a CSV file of sales into a polished statistical report.