Skip to main content

A Python implementation of the Result monad pattern, inspired by Kotlin

Project description

kotresult

image image image image image Unittest

A Python implementation of the Result monad pattern, inspired by Kotlin's Result class. This library provides a way to handle operations that might succeed or fail without using exceptions for control flow.

Installation

You can install the package via pip:

pip install kotresult

Usage

Result Class

The Result class represents an operation that might succeed or fail. It can contain either a successful value or an exception.

from kotresult import Result

# Create a success result
success = Result.success("Hello, World!")
print(success.is_success)  # True
print(success.get_or_none())  # "Hello, World!"

# Create a failure result
failure = Result.failure(ValueError("Something went wrong"))
print(failure.is_failure)  # True
print(failure.exception_or_none())  # ValueError("Something went wrong")

Getting Values Safely

# Get the value or a default
value = success.get_or_default("Default value")  # "Hello, World!"
value = failure.get_or_default("Default value")  # "Default value"

# Get the value or throw the exception
try:
    value = failure.get_or_throw()  # Raises ValueError("Something went wrong")
except ValueError as e:
    print(f"Caught exception: {e}")

# Throw on failure
success.throw_on_failure()  # Does nothing
try:
    failure.throw_on_failure()  # Raises ValueError("Something went wrong")
except ValueError as e:
    print(f"Caught exception: {e}")

run_catching Function

The run_catching function executes a function and returns a Result object containing either the return value or any exception that was raised.

from kotresult import run_catching


# With a function that succeeds
def add(a, b):
    return a + b


result = run_catching(add, 2, 3)
print(result.is_success)  # True
print(result.get_or_none())  # 5


# With a function that fails
def divide(a, b):
    return a / b


result = run_catching(divide, 1, 0)  # ZeroDivisionError
print(result.is_failure)  # True
print(type(result.exception_or_none()))  # <class 'ZeroDivisionError'>


# With keyword arguments
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"


result = run_catching(greet, name="World", greeting="Hi")
print(result.get_or_none())  # "Hi, World!"

API Reference

Result Class

Static Methods

  • Result.success(value): Creates a success result with the given value
  • Result.failure(exception): Creates a failure result with the given exception

Properties

  • is_success: Returns True if the result is a success, False otherwise
  • is_failure: Returns True if the result is a failure, False otherwise

Methods

  • get_or_none(): Returns the value if success, None if failure
  • exception_or_none(): Returns the exception if failure, None if success
  • to_string(): Returns a string representation of the result
  • get_or_default(default_value): Returns the value if success, the default value if failure
  • get_or_throw(): Returns the value if success, throws the exception if failure
  • throw_on_failure(): Throws the exception if failure, does nothing if success

run_catching Function

  • run_catching(func, *args, **kwargs): Executes the function with the given arguments and returns a Result object

License

This project is licensed under the MIT License - see the LICENSE file for details.

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

kotresult-0.1.0.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kotresult-0.1.0-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file kotresult-0.1.0.tar.gz.

File metadata

  • Download URL: kotresult-0.1.0.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for kotresult-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f555a1601a674437f9e5c6dca363500e0c354b085d6fa85ad6db9753ae05ada5
MD5 617d3b69e11fd143b0b3a6344e881b9d
BLAKE2b-256 ef1de942a6a4b0245dbfb7a2918e4903af238096ecdd4df2e9ac80230c0ab670

See more details on using hashes here.

File details

Details for the file kotresult-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: kotresult-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for kotresult-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2750c2ded3228156203795e672ab9fde5d210b985d44baf40dd307564f865e1b
MD5 cc29f5fec56f5fc538010fb6ecadee0b
BLAKE2b-256 d89d42b831b0cb4e9e38d14db4ef144f61dd627469fdcedaefe29d5f1db322f8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page