DataAndMsgReturn to handle both success and failure paths, check the result with a clean if result.ok branch, and serialize the output to a plain dictionary using to_dict() — all in under five minutes.
1
Install BasicReturns
Install the package from PyPI using pip:To pin to the current stable release (recommended for production):BasicReturns requires Python >= 3.8 and will automatically install its only dependency,
pydantic==2.12.5.2
Import the models
Both classes live at the top-level
BasicReturns package. Import whichever ones you need:- Use
BasicReturnfor operations that don’t return a data payload (writes, saves, deletes). - Use
DataAndMsgReturnfor operations that compute or fetch something the caller will consume.
3
Write a function with DataAndMsgReturn
The pattern is always the same: create a default response object, populate its fields inside a Notice what happens in each path:
try/except, and return it. Here is the canonical example from the project docs:- Success —
okstays at its defaultTrue,datareceives the result, andmsgrecords a human-readable summary. - Failure —
okis explicitly set toFalse,errorcaptures the exception, andmsgdescribes what went wrong.
4
Handle the result
Every caller uses the same
if result.ok pattern regardless of which function returned the value. No more guessing whether to catch an exception or check for None:5
Serialize with to_dict()
Both When
BasicReturn and DataAndMsgReturn expose a to_dict() method that returns a plain Python dictionary. This is useful for JSON responses, logging, or passing data across service boundaries:data is None (the default on a failure path), to_dict() returns {} for the data key so downstream consumers always receive a consistent, non-null structure.Both Classes Side by Side
The two models follow the same pattern. Choose based on whether your function produces a data payload.These examples use simple patterns to get you started quickly. The Guides section covers real-world scenarios in depth — including chaining multiple operations, propagating errors between functions, and integrating BasicReturns into API layers and file utilities.