Skip to main content
By the end of this guide you will have BasicReturns installed, imported, and running in your project. You’ll write a real function that uses 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 BasicReturn for operations that don’t return a data payload (writes, saves, deletes).
  • Use DataAndMsgReturn for 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 try/except, and return it. Here is the canonical example from the project docs:
Notice what happens in each path:
  • Success — ok stays at its default True, data receives the result, and msg records a human-readable summary.
  • Failure — ok is explicitly set to False, error captures the exception, and msg describes 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 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:
When 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.
Because ok defaults to True, you only need to touch it on the failure path. On the success path, simply populate data and msg and return — ok is already correct. This keeps the happy path clean and the error path explicit.

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.