Skip to content

Latest commit

History

13 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

BasicReturns 🐍

DeepWiki

PyPI VersionPyPI - Python VersionPyPI - LicensePyPI Downloads


Check This:

image

Standardizes function return values across Python applications to enhance code consistency, readability, and maintainability.

📦 Installation

pip install BasicReturns

🚀 Quick Start

fromBasicReturnsimportBasicReturn, DataAndMsgReturndefdivide_numbers(a: float, b: float) ->DataAndMsgReturn:
"""Safely divide two numbers with unified return structure."""response=DataAndMsgReturn()
try:
ifb==0:
raiseZeroDivisionError("Cannot divide by zero")
response.data=a/bresponse.msg="Division completed successfully"exceptExceptionase:
response.ok=Falseresponse.error=eresponse.msg="Division failed"returnresponse# Usage exampleresult=divide_numbers(10, 2)
ifresult.ok:
print(f"{result.msg}: {result.data}") # Division completed successfully: 5.0else:
print(f"{result.msg}: {result.error}") # Division failed: Cannot divide by zero

🛠️ Practical Examples

File Operations Utility

Here's how to implement a file utility class using unified returns:

fromioimportTextIOWrapperfrompathlibimportPathimportjsonfromtypingimportAnyfromBasicReturnsimportBaseReturn, DataAndMsgReturnclassFilesUtils:
@staticmethoddeffile_exists(filename: str) ->bool:
returnPath(filename).is_file()
@staticmethoddefread_file(filename: str) ->DataAndMsgReturn:
"""Read file content with unified return structure."""response=DataAndMsgReturn()
try:
ifnotFilesUtils.file_exists(filename):
response.ok=Falseresponse.error=FileNotFoundError(f"File '{filename}' not found")
response.msg="File does not exist"returnresponsewithopen(filename, 'r', encoding='utf-8') asfile:
response.data=file.read()
response.msg=f"Successfully read file: {filename}"exceptExceptionase:
response.ok=Falseresponse.error=eresponse.msg=f"Error reading file: {filename}"returnresponse@staticmethoddefread_json(filename: str) ->DataAndMsgReturn:
"""Read and parse JSON file with unified error handling."""response=DataAndMsgReturn()
file_result=FilesUtils.read_file(filename)
ifnotfile_result.ok:
# Propagate the error from read_fileresponse.ok=file_result.okresponse.error=file_result.errorresponse.msg=file_result.msgreturnresponsetry:
response.data=json.loads(file_result.data)
response.msg=f"Successfully parsed JSON from: {filename}"exceptjson.JSONDecodeErrorase:
response.ok=Falseresponse.error=eresponse.msg=f"Invalid JSON format in file: {filename}"returnresponse@staticmethoddefwrite_json(filename: str, data: dict) ->BaseReturn:
"""Write dictionary to JSON file with atomic operation handling."""response=BaseReturn()
try:
withopen(filename, 'w', encoding='utf-8') asfile:
json.dump(data, file, indent=2, sort_keys=True, ensure_ascii=False)
response.msg=f"Successfully wrote JSON to: {filename}"exceptExceptionase:
response.ok=Falseresponse.error=eresponse.msg=f"Failed to write JSON file: {filename}"returnresponse

Usage in Application

# Read configuration fileconfig_result=FilesUtils.read_json("config.json")
ifconfig_result.ok:
config=config_result.dataprint("Configuration loaded:", config)
else:
print("Error loading config:", config_result.error)
# Fallback to default configurationconfig= {"default": "settings"}
# Save user datauser_data= {"name": "John Doe", "email": "john@example.com"}
save_result=FilesUtils.write_json("users/john.json", user_data)
ifsave_result.ok:
print("User data saved successfully")
else:
print("Failed to save user data:", save_result.error)
# Handle the error appropriately

🌟 Best Practices

1. Consistent Error Handling

defprocess_data(data: Any) ->DataAndMsgReturn:
response=DataAndMsgReturn()
ifnotdata:
response.ok=Falseresponse.error=ValueError("Empty data provided")
response.msg="Validation failed"returnresponse# Process data...response.data=processed_dataresponse.msg="Data processed successfully"returnresponse

2. Chaining Operations

defload_and_validate_config() ->DataAndMsgReturn:
config_result=FilesUtils.read_json("config.json")
ifnotconfig_result.ok:
returnconfig_result# Return the error immediatelyvalidation_result=validate_config(config_result.data)
ifnotvalidation_result.ok:
returnDataAndMsgReturn(
ok=False,
error=validation_result.error,
msg=f"Configuration validation failed: {validation_result.msg}"
)
returnDataAndMsgReturn(
data=config_result.data,
msg="Configuration loaded and validated successfully"
)

3. API Integration

importrequestsfromBasicReturnsimportDataAndMsgReturndeffetch_api_data(url: str) ->DataAndMsgReturn:
response=DataAndMsgReturn()
try:
api_response=requests.get(url, timeout=10)
api_response.raise_for_status()
response.data=api_response.json()
response.msg=f"Successfully fetched data from {url}"exceptrequests.exceptions.RequestExceptionase:
response.ok=Falseresponse.error=eresponse.msg=f"API request failed: {url}"returnresponse

📊 Benefits

Consistent Error Handling - No more guessing return types or error formats
Improved Readability - Clear success/failure states with contextual messages
Better Debugging - Structured error information with stack traces when needed
Type Safety - Full MyPy compatibility with proper type annotations
Seamless Integration - Works with any Python framework or application
Serialization Ready - Built-in to_dict() method for JSON/API responses

🤝 Contributing

Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.

  1. Fork the repository
  2. Create your feature branch (git switch -c feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a pull request

📄 License

Distributed under the MIT License. See LICENSE for more information.


Made with ❤️ for Python developers who value clean, consistent code

About

Python Basic Returns - Pypi Package. Standardizes function return values across Python applications to enhance code consistency, readability, and maintainability.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages