Bring some useful tools from Rust to Python
Project description
rusty-utils
Bringing useful tools from Rust to Python.
:door: Portals
:inbox_tray: Installation
rusty-utils
is available on PyPI.
Install using pip
:
pip install rusty-utils
Or with poetry
:
poetry add rusty-utils
:books: Features
rusty-utils
brings Rust-inspired constructs like Result
and Option
to Python, allowing developers to write cleaner
and more robust error-handling code.
For more details, check out the full documentation.
Result[T, E]
The Result
type is inspired by Rust, enabling you to handle success (Ok
) and failure (Err
) in a clean, expressive
way.
from rusty_utils import Result, Ok, Err
# Success case
success: Result[int, Exception] = Ok(42)
# Failure case
failure: Result[int, Exception] = Err(Exception("An error occurred"))
Custom Result Types
You can alias your own custom Result
types to suit your domain-specific needs.
from typing import TypeVar
from rusty_utils import Result, Ok, Err
class MyError(Exception): pass
_T = TypeVar("_T")
MyResult = Result[_T, MyError]
# Custom success and failure cases
success: MyResult[int] = Ok(42)
failure: MyResult[int] = Err(MyError("Something went wrong"))
Quickly wrap a function call
import random
from rusty_utils import Catch, Result
# Let's assume this function may fail
def russian_roulette() -> str:
if random.randint(0, 6) == 0:
raise Exception("Bang!")
else:
return "Click!"
# Quickly wrap the function call in a Result
result: Result[str, Exception] = Catch(russian_roulette, Exception)
API Overview
-
Querying Result Type:
is_ok()
: ReturnsTrue
if theResult
isOk
.is_err()
: ReturnsTrue
if theResult
isErr
.
-
Unwrapping Values:
expect(message)
: Unwraps the value or raisesUnwrapError
with a custom message.unwrap()
: Unwraps the value or raisesUnwrapError
.unwrap_or(default)
: Returns the provided default value ifErr
.unwrap_or_else(func)
: Returns the result of the provided function ifErr
.unwrap_or_raise()
: Raises the exception contained inErr
.
-
Transforming Results:
map(func)
: Transforms theOk
value.map_err(func)
: Transforms theErr
value.map_or(default, func)
: Appliesfunc
toOk
or returnsdefault
ifErr
.map_or_else(f_err, f_ok)
: Applies different functions depending on whether theResult
isOk
orErr
.
-
Logical Operations:
and_(other)
: Returns the secondResult
if the first isOk
; otherwise returns the originalErr
.or_(other)
: Returns the firstOk
, or the secondResult
if the first isErr
.and_then(func)
: Chains another operation based on theOk
value.or_else(func)
: Chains another operation based on theErr
value.
Option[T]
The Option
type expands Python's Optional
, representing a value that may or may not be present (Some
or None
).
from rusty_utils import Option
some_value: Option[int] = Option(42)
none_value: Option[int] = Option()
API Overview
-
Querying Option Type:
is_some()
: ReturnsTrue
if theOption
contains a value.is_none()
: ReturnsTrue
if theOption
contains no value.
-
Unwrapping Values:
expect(message)
: Unwraps the value or raisesUnwrapError
with a custom message.unwrap()
: Unwraps the value or raisesUnwrapError
.unwrap_or(default)
: Returns the provided default value ifNone
.unwrap_or_else(func)
: Returns the result of a provided function ifNone
.
-
Transforming Options:
map(func)
: Transforms theSome
value.map_or(default, func)
: Transforms theSome
value or returns a default ifNone
.map_or_else(default_func, func)
: Transforms theSome
value or returns the result of a default function ifNone
.
-
Logical Operations:
and_(other)
: Returns the secondOption
if the first isSome
; otherwise returnsNone
.or_(other)
: Returns the firstSome
, or the secondOption
if the first isNone
.and_then(func)
: Chains another operation based on theSome
value.or_else(func)
: Chains another operation based on theNone
value.
:gear: Usage Examples
Here are more practical examples of using Result
and Option
in real-world scenarios.
Example: Handling API Responses
from rusty_utils import Result, Ok, Err
def fetch_data() -> Result[dict, Exception]:
try:
# Simulating an API call
data = {"id": 824, "name": "Kobe Bryant"}
return Ok(data)
except Exception as e:
return Err(e)
result = fetch_data()
if result.is_ok():
print("Success:", result.unwrap())
else:
print("Error:", result.unwrap_err())
Example: Safely Unwrapping Values
from rusty_utils import Option
def get_value() -> Option[int]:
return Option(42)
some_value = get_value()
print(some_value.unwrap_or(0)) # Outputs: 42
For more advanced use cases, consult the full documentation.
Project details
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
File details
Details for the file rusty_utils-0.1.1.tar.gz
.
File metadata
- Download URL: rusty_utils-0.1.1.tar.gz
- Upload date:
- Size: 8.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.12.5 Windows/10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 66ea90f50f329e6cb0adb3a6090e106646624e65166081016eaade9b90160dc1 |
|
MD5 | 88e1da861561bf8f8c3509268066b8af |
|
BLAKE2b-256 | fda9a2cbfd7a047cb8ff3dc0deca5b44a7b05776f0ae676be86cb064f1d2c284 |
Provenance
File details
Details for the file rusty_utils-0.1.1-py3-none-any.whl
.
File metadata
- Download URL: rusty_utils-0.1.1-py3-none-any.whl
- Upload date:
- Size: 8.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.12.5 Windows/10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9140e436fe86ab5fd47c241d2db20489bb9dcfedae23cf7f96d6a6b0a41c8843 |
|
MD5 | e794f9545eaf3ddc2b0d9f437ade7889 |
|
BLAKE2b-256 | c8ea2f79a08ef57a1612285ef757a35b63281f921e2e166ad9b92d613012c232 |