Python builtins wrapped with rust-like Result
Project description
safe-builtins
Python's builtins wrapped inside rust-like Result type
[!WARNING] This library doesn't depend on original python Result library, instead it depends on my fork which is up-to-date with the one maintained by @montasaurus, as per this README is written, it's still labeled as experimental and unstable, so use this library at your own risk!
Installation
Install the package from PyPi using uv:
uv add safe-builtins
or install it directly from master branch on github for the latest update
uv add git+https://github.com/kkkfasy/safe-builtins
[!WARNING] Since
uvdoesnt support downloading transitive dependency from custom registry (in this case github), you need to run
uv add git+https://github.com/kkkfasy/result
you dont need to run this if you install from github directly
Summary
This library provides safe wrappers for Python's built-in functions using the Result type from the montasaurus/result library. Instead of raising exceptions, these functions return a Result that either contains the successful value (Ok) or the caught exception (Err).
This approach eliminates the need for extensive try/except blocks and makes error handling more explicit and functional in style.
API
Creating Safe Builtins
Each Python builtin function has a corresponding safe_ prefixed version:
from safe_builtins import safe_int, safe_open, safe_len
# Instead of raising ValueError, returns Err(ValueError(...))
result = safe_int("not a number")
# Returns Ok(42)
result = safe_int("42")
# Instead of raising FileNotFoundError, returns Err(FileNotFoundError(...))
result = safe_open("non_existent_file.txt")
# Returns Ok(file_object)
result = safe_open("existing_file.txt")
# Instead of raising TypeError, returns Err(TypeError(...))
result = safe_len(123) # integers don't have length
# Returns Ok(3)
result = safe_len([1, 2, 3])
Checking Results
You can check if a result is successful or contains an error:
from safe_builtins import safe_int
from result import Ok, Err
result = safe_int("42")
# Using isinstance checks
if isinstance(result, Ok):
value = result.unwrap()
print(f"Got value: {value}")
elif isinstance(result, Err):
error = result.unwrap_err()
print(f"Got error: {error}")
# Using is_ok/is_err methods
if result.is_ok():
value = result.unwrap()
print(f"Got value: {value}")
elif result.is_err():
error = result.unwrap_err()
print(f"Got error: {error}")
Accessing Values
from safe_builtins import safe_int
from result import Ok
result = safe_int("42")
# Get the value or raise an exception if it's an error
value = result.unwrap()
# Get the value or a default if it's an error
value = result.unwrap_or(0)
# Get the value or compute a default if it's an error
value = result.unwrap_or_else(lambda err: 0)
# Convert to optional (None if error)
optional_value = result.ok()
Chaining Operations
from safe_builtins import safe_int, safe_open
from result import Ok
# Chain operations that might fail
result = (
safe_int("42")
.map(lambda x: x * 2) # Only executed if the result is Ok
.map_err(lambda err: f"Error processing number: {err}") # Only executed if the result is Err
)
# Process file contents safely
result = (
safe_open("data.txt")
.map(lambda f: f.read()) # Read file contents
.map(lambda contents: contents.splitlines()) # Split into lines
.map(lambda lines: len(lines)) # Count lines
)
Available Safe Builtins
The following Python builtins are available as safe versions:
safe_abssafe_aitersafe_allsafe_anysafe_anextsafe_asciisafe_binsafe_breakpointsafe_bytearraysafe_bytessafe_chrsafe_compilesafe_complexsafe_delattrsafe_dictsafe_dirsafe_divmodsafe_enumeratesafe_evalsafe_execsafe_filtersafe_floatsafe_formatsafe_frozensetsafe_getattrsafe_hashsafe_hexsafe_idsafe_inputsafe_intsafe_isinstancesafe_issubclasssafe_itersafe_lensafe_listsafe_mapsafe_maxsafe_memoryviewsafe_minsafe_nextsafe_objectsafe_octsafe_opensafe_ordsafe_powsafe_rangesafe_reversedsafe_roundsafe_setsafe_setattrsafe_slicesafe_sortedsafe_staticmethodsafe_strsafe_sumsafe_supersafe_tuplesafe_typesafe_varssafe_zipsafe_importsafe_bool
Related Projects
- result - The underlying Result type implementation
- returns - Another functional approach to error handling in Python
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file safe_builtins-0.2.1.tar.gz.
File metadata
- Download URL: safe_builtins-0.2.1.tar.gz
- Upload date:
- Size: 52.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d1a851129cf3517b73c80035367793306d574fa3705c81d3b5995e95fafd24b0
|
|
| MD5 |
e7d3fc6009c4a83261d6c594b19cb733
|
|
| BLAKE2b-256 |
7148c4ee16eedd6ea2cd011ec30d84504c60d900770df039e05b5e130accd26d
|
File details
Details for the file safe_builtins-0.2.1-py3-none-any.whl.
File metadata
- Download URL: safe_builtins-0.2.1-py3-none-any.whl
- Upload date:
- Size: 6.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d033367ce98d1db041f9a0d06b9d298c36f487ec7648b9e683695649abca9c03
|
|
| MD5 |
3f6798bb3705ba6530d08868be2d2ab4
|
|
| BLAKE2b-256 |
d231983bfc9c0628b3918018d81db80d29657a17f762b6b3a3899ae7c5144218
|