Model an inventory item with validation
Python data engineering interview problem. Difficulty: intermediate. Pattern: OOP. About 15 minutes. Part of the Pro drill bank.
Inventory items cannot exist with a negative quantity. Construction should reject bad data; a helper may return None for callers that prefer not to catch exceptions.
An inventory system must never hold an item with a negative quantity. The class should refuse to be created with a bad quantity, and a safe helper should turn that refusal into None. Write a class InventoryItem(sku, qty) that raises ValueError if qty is negative. Give it a method receive(n) that adds n to the quantity and raises ValueError if n is 0 or less. Also write safe_make(sku, qty) that returns {'sku': ..., 'qty': ...} for a good item and None when the item cannot be created. Write safe_make(sku, qty). safe_make('A', 2) returns {'sku': 'A', 'qty': 2}. safe_make('A', -1) returns None, because a negative quantity is not allowed. The starter file already has the function name and its print lines. Keep them and fill in the body.
Requirements
- InventoryItem rejects a negative qty with ValueError.
- receive(n) adds to qty and rejects n <= 0.
- safe_make returns a dictionary for valid items.
- safe_make returns None instead of raising.
Constraints
- Zero is a valid quantity.
- safe_make must catch the error and not let it escape.
Examples
Input: safe_make('A', 2) Output: {'sku': 'A', 'qty': 2} This input follows the stated rules and produces this output.
Topics: lakebench, python, OOP.
More Python interview questions · All interview problems · Learn data engineering
Model an inventory item with validation
Interview-style drill: Define a class representing an inventory item that rejects a negative quantity on construction.
Model InventoryItem so invalid quantities cannot be constructed, and implement `safe_make` as a non-throwing wrapper.