DrResult


NameDrResult JSON
Version 0.6.5 PyPI version JSON
download
home_pageNone
SummaryNone
upload_time2024-10-17 23:51:45
maintainerNone
docs_urlNone
authorOle Kliemann
requires_python>=3.12
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![tests](https://github.com/olekli/drresult/actions/workflows/pytest-coverage.yml/badge.svg)
[![codecov](https://codecov.io/github/olekli/DrResult/branch/main/graph/badge.svg?token=WLSOABF6I6)](https://codecov.io/github/olekli/DrResult)
[![Documentation Status](https://readthedocs.org/projects/drresult/badge/?version=latest)](https://drresult.readthedocs.io/en/latest/?badge=latest)
[![PyPI version](https://badge.fury.io/py/DrResult.svg)](https://badge.fury.io/py/DrResult)

# DrResult

More radical approach to Rust's `std::result` in Python.

## Motivation

I do not want exceptions in my code.
Rust has this figured out quite neatly
by essentially revolving around two pathways for errors:
A possible error condition is either one that has no prospect of being handled
-- then the program should terminate -- or it is one that could be handled --
then it has to be handled or explicitly ignored.

This concept is replicated here by using mapping all unhandled exceptions to `Panic`
and providing a Rust-like `result` type to signal error conditions that do not need to terminate
the program.

## Documentation

### Concept

At each point in your code, there are exceptions that are considered to be expected
and there are exceptions that are considered unexpected.

In general, an unexpected exception will be mapped to `Panic`.
No part of DrResult will attempt to handle a `Panic` exception.
And you should leave all exception handling to DrResult,
i.e. have no `try/except` blocks in your code.
In any case, you should never catch `Panic`.
An unexpected exception will therefore result in program termination with stack unwinding.

You will need to specify which exceptions are to be expected.
There are two modes of operation here:
You can explicitly name the exceptions to be expected in a function.
Or you can skip that and basically expect all exceptions.

_Basically_ means: By default only `Exception` is expected, not `BaseException`.
And even of type `Exception` that are some considered to be never expected:
```python
AssertionError, AttributeError, ImportError, MemoryError, NameError, SyntaxError, SystemError, TypeError
```
If you do not explicitly expect these, they will be implicitly unexpected.
(Obviously, the exact list may be up for debate.)

### Basic Usage

#### `@noexcept`

If your function knows no errors, you mark it as `@noexcept()`:

```python
from drresult import noexcept

@noexcept()
def sum(a: list) -> int:
    result = 0
    for item in a:
        result += item
    return result

result = func([1, 2, 3])
```

This will do what you expect it does.
But if you screw up...
```python
@noexcept()
def sum(a: list) -> int:
    result = 0
    for item in a:
        result += item
    print(a[7])   # IndexError
    return result

result = func([1, 2, 3])    # Panic!
```
... then it will raise `Panic` preserving the stack trace and the original exception.

This way all unexpected exceptions are normalised to `Panic`.

Please note that a `@noexecpt` function does not return a result but just the return type itself.

#### `@returns_result()` and `expects`

Marking a function as `@returns_result` will wrap any exceptions thrown in an `Err` result.
But only those exceptions that are expected.
As noted above, if you do not explicitly specify exceptions to expect,
most runtime exceptions are expected by default.

```python
@returns_result()
def read_file() -> Result[str]:
    with open('/some/path/that/might/be/invalid') as f:
        return Ok(f.read())

result = read_file()
if result.is_ok():
    print(f'File content: {result.unwrap()}')
else:
    print(f'Error: {str(result.unwrap_err())}')
```

This will do as you expect.

You can also explicitly specify the exception to expect:
```python
@returns_result(expects=[FileNotFoundError])
def read_file() -> Result[str]:
    with open('/some/path/that/might/be/invalid') as f:
        return Ok(f.read())

result = read_file()
if result.is_ok():
    print(f'File content: {result.unwrap()}')
else:
    print(f'Error: {str(result.unwrap_err())}')
```
This also will do as you expect.

If fail to specify an exception that is raised as expected...
```python
from drresult import returns_result

@returns_result(expects=[IndexError, KeyError])
def read_file() -> Result[str]:
    with open('/this/path/is/invalid') as f:
        return Ok(f.read())

result = read_file()    # Panic!
```
.. it will be re-raised as `Panic`.

If you are feeling fancy, you can also do pattern matching:
```python
@returns_result(expects=[FileNotFoundError])
def read_file() -> Result[str]:
    with open('/this/path/is/invalid') as f:
        return Ok(f.read())

result = read_file()
match result:
    case Ok(v):
        print(f'File content: {v}')
    case Err(e):
        print(f'Error: {e}')
```

And even fancier:
```python
data = [{ 'foo': 'value-1' }, { 'bar': 'value-2' }]

@returns_result(expects=[IndexError, KeyError, RuntimeError])
def retrieve_record_entry_backend(index: int, key: str) -> Result[str]:
    if key == 'baz':
        raise RuntimeError('Cannot process baz!')
    return Ok(data[index][key])

def retrieve_record_entry(index: int, key: str):
    match retrieve_record_entry_backend(index: int, key: str):
        case Ok(v):
            print(f'Retrieved: {v}')
        case Err(IndexError()):
            print(f'No such record: {index}')
        case Err(KeyError()):
            print(f'No entry `{key}` in record {index}')
        case Err(RuntimeError() as e):
            print(f'Error: {e}')

retrieve_record_entry(2, 'foo')    # No such record: 2
retrieve_record_entry(1, 'foo')    # No entry `foo` in record 1
retrieve_record_entry(1, 'bar')    # Retrieved: value-2
retrieve_record_entry(1, 'baz')    # Error: Cannot process baz!
```


#### Implicit conversion to bool

If you are feeling more lazy than fancy, you can do this:
```python
result = Ok('foo')
assert result

result = Err('bar')
assert not result
```


#### `unwrap_or_raise`

You can replicate the behaviour of Rust's `?`-operator with `unwrap_or_raise`:
```python
@returns_result()
def read_json(filename: str) -> Result[str]:
    with open(filename) as f:
        return Ok(json.loads(f.read()))

@returns_result()
def parse_file(filename: str) -> Result[dict]:
    content = read_file(filename).unwrap_or_raise()
    if not 'required_key' in content:
        raise KeyError('required_key')
    return Ok(content)
```
If the result is not `Ok`, `unwrap_or_raise()` will re-raise the contained exception.
Obviously, this will lead to an assertion if the contained exception is not expected.


#### `gather_result`

When you are interfacing with other modules that use exceptions,
you may want to react to certain exceptions being raised.
To avoid having to use `try/except` again,
you can transform exceptions from a part of your code to results:

```python
@returns_result()
def parse_json_file(filename: str) -> Result[dict]:
    with gather_result() as result:
        with open(filename) as f:
            result.set(Ok(json.loads(f.read())))
    result = result.get()
    match result:
        case Ok(data):
            return Ok(data)
        case Err(FileNotFoundError()):
            return Ok({})
        case _:
            return result
```

#### Printing the Stack Trace

If you want to format the exception stored in `Err`,
you can use `Err.__str__()` and `Err.trace()`.
The former will just provide the error message itself
where the latter will provide the entire stack trace.
The trace is filtered to remove all intermediate frames for internal functions.

Also, DrResult overrides the `expecthook` to filter the stack trace in case of panic.

#### `constructs_as_result`

If you have a class that might raise an error in its constructor,
you can mark it as `constructs_as_result`:

```python
@constructs_as_result
class Reader:
    def __init__(self, filename):
        with open(filename) as f:
            self.data = json.loads(f.read())
```
Creating an instance of this class will yield a `Result` that has to be unwrapped first.
```python
reader = Reader('/path/to/existing/file').unwrap() # Ok
reader = Reader('/invalid/path/to/non/existing/file').unwrap() # panic!
```

## Similar Projects

For a less extreme approach on Rust's result type, see:

* [https://github.com/rustedpy/result](https://github.com/rustedpy/result)
* [https://github.com/felixhammerl/resultify](https://github.com/felixhammerl/resultify)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "DrResult",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": null,
    "keywords": null,
    "author": "Ole Kliemann",
    "author_email": "mail@olekliemann.de",
    "download_url": "https://files.pythonhosted.org/packages/42/8c/5ba4966ab27d32f424e6aecc13e1149b4772b26dd7d463ed6e8689332922/drresult-0.6.5.tar.gz",
    "platform": null,
    "description": "![tests](https://github.com/olekli/drresult/actions/workflows/pytest-coverage.yml/badge.svg)\n[![codecov](https://codecov.io/github/olekli/DrResult/branch/main/graph/badge.svg?token=WLSOABF6I6)](https://codecov.io/github/olekli/DrResult)\n[![Documentation Status](https://readthedocs.org/projects/drresult/badge/?version=latest)](https://drresult.readthedocs.io/en/latest/?badge=latest)\n[![PyPI version](https://badge.fury.io/py/DrResult.svg)](https://badge.fury.io/py/DrResult)\n\n# DrResult\n\nMore radical approach to Rust's `std::result` in Python.\n\n## Motivation\n\nI do not want exceptions in my code.\nRust has this figured out quite neatly\nby essentially revolving around two pathways for errors:\nA possible error condition is either one that has no prospect of being handled\n-- then the program should terminate -- or it is one that could be handled --\nthen it has to be handled or explicitly ignored.\n\nThis concept is replicated here by using mapping all unhandled exceptions to `Panic`\nand providing a Rust-like `result` type to signal error conditions that do not need to terminate\nthe program.\n\n## Documentation\n\n### Concept\n\nAt each point in your code, there are exceptions that are considered to be expected\nand there are exceptions that are considered unexpected.\n\nIn general, an unexpected exception will be mapped to `Panic`.\nNo part of DrResult will attempt to handle a `Panic` exception.\nAnd you should leave all exception handling to DrResult,\ni.e. have no `try/except` blocks in your code.\nIn any case, you should never catch `Panic`.\nAn unexpected exception will therefore result in program termination with stack unwinding.\n\nYou will need to specify which exceptions are to be expected.\nThere are two modes of operation here:\nYou can explicitly name the exceptions to be expected in a function.\nOr you can skip that and basically expect all exceptions.\n\n_Basically_ means: By default only `Exception` is expected, not `BaseException`.\nAnd even of type `Exception` that are some considered to be never expected:\n```python\nAssertionError, AttributeError, ImportError, MemoryError, NameError, SyntaxError, SystemError, TypeError\n```\nIf you do not explicitly expect these, they will be implicitly unexpected.\n(Obviously, the exact list may be up for debate.)\n\n### Basic Usage\n\n#### `@noexcept`\n\nIf your function knows no errors, you mark it as `@noexcept()`:\n\n```python\nfrom drresult import noexcept\n\n@noexcept()\ndef sum(a: list) -> int:\n    result = 0\n    for item in a:\n        result += item\n    return result\n\nresult = func([1, 2, 3])\n```\n\nThis will do what you expect it does.\nBut if you screw up...\n```python\n@noexcept()\ndef sum(a: list) -> int:\n    result = 0\n    for item in a:\n        result += item\n    print(a[7])   # IndexError\n    return result\n\nresult = func([1, 2, 3])    # Panic!\n```\n... then it will raise `Panic` preserving the stack trace and the original exception.\n\nThis way all unexpected exceptions are normalised to `Panic`.\n\nPlease note that a `@noexecpt` function does not return a result but just the return type itself.\n\n#### `@returns_result()` and `expects`\n\nMarking a function as `@returns_result` will wrap any exceptions thrown in an `Err` result.\nBut only those exceptions that are expected.\nAs noted above, if you do not explicitly specify exceptions to expect,\nmost runtime exceptions are expected by default.\n\n```python\n@returns_result()\ndef read_file() -> Result[str]:\n    with open('/some/path/that/might/be/invalid') as f:\n        return Ok(f.read())\n\nresult = read_file()\nif result.is_ok():\n    print(f'File content: {result.unwrap()}')\nelse:\n    print(f'Error: {str(result.unwrap_err())}')\n```\n\nThis will do as you expect.\n\nYou can also explicitly specify the exception to expect:\n```python\n@returns_result(expects=[FileNotFoundError])\ndef read_file() -> Result[str]:\n    with open('/some/path/that/might/be/invalid') as f:\n        return Ok(f.read())\n\nresult = read_file()\nif result.is_ok():\n    print(f'File content: {result.unwrap()}')\nelse:\n    print(f'Error: {str(result.unwrap_err())}')\n```\nThis also will do as you expect.\n\nIf fail to specify an exception that is raised as expected...\n```python\nfrom drresult import returns_result\n\n@returns_result(expects=[IndexError, KeyError])\ndef read_file() -> Result[str]:\n    with open('/this/path/is/invalid') as f:\n        return Ok(f.read())\n\nresult = read_file()    # Panic!\n```\n.. it will be re-raised as `Panic`.\n\nIf you are feeling fancy, you can also do pattern matching:\n```python\n@returns_result(expects=[FileNotFoundError])\ndef read_file() -> Result[str]:\n    with open('/this/path/is/invalid') as f:\n        return Ok(f.read())\n\nresult = read_file()\nmatch result:\n    case Ok(v):\n        print(f'File content: {v}')\n    case Err(e):\n        print(f'Error: {e}')\n```\n\nAnd even fancier:\n```python\ndata = [{ 'foo': 'value-1' }, { 'bar': 'value-2' }]\n\n@returns_result(expects=[IndexError, KeyError, RuntimeError])\ndef retrieve_record_entry_backend(index: int, key: str) -> Result[str]:\n    if key == 'baz':\n        raise RuntimeError('Cannot process baz!')\n    return Ok(data[index][key])\n\ndef retrieve_record_entry(index: int, key: str):\n    match retrieve_record_entry_backend(index: int, key: str):\n        case Ok(v):\n            print(f'Retrieved: {v}')\n        case Err(IndexError()):\n            print(f'No such record: {index}')\n        case Err(KeyError()):\n            print(f'No entry `{key}` in record {index}')\n        case Err(RuntimeError() as e):\n            print(f'Error: {e}')\n\nretrieve_record_entry(2, 'foo')    # No such record: 2\nretrieve_record_entry(1, 'foo')    # No entry `foo` in record 1\nretrieve_record_entry(1, 'bar')    # Retrieved: value-2\nretrieve_record_entry(1, 'baz')    # Error: Cannot process baz!\n```\n\n\n#### Implicit conversion to bool\n\nIf you are feeling more lazy than fancy, you can do this:\n```python\nresult = Ok('foo')\nassert result\n\nresult = Err('bar')\nassert not result\n```\n\n\n#### `unwrap_or_raise`\n\nYou can replicate the behaviour of Rust's `?`-operator with `unwrap_or_raise`:\n```python\n@returns_result()\ndef read_json(filename: str) -> Result[str]:\n    with open(filename) as f:\n        return Ok(json.loads(f.read()))\n\n@returns_result()\ndef parse_file(filename: str) -> Result[dict]:\n    content = read_file(filename).unwrap_or_raise()\n    if not 'required_key' in content:\n        raise KeyError('required_key')\n    return Ok(content)\n```\nIf the result is not `Ok`, `unwrap_or_raise()` will re-raise the contained exception.\nObviously, this will lead to an assertion if the contained exception is not expected.\n\n\n#### `gather_result`\n\nWhen you are interfacing with other modules that use exceptions,\nyou may want to react to certain exceptions being raised.\nTo avoid having to use `try/except` again,\nyou can transform exceptions from a part of your code to results:\n\n```python\n@returns_result()\ndef parse_json_file(filename: str) -> Result[dict]:\n    with gather_result() as result:\n        with open(filename) as f:\n            result.set(Ok(json.loads(f.read())))\n    result = result.get()\n    match result:\n        case Ok(data):\n            return Ok(data)\n        case Err(FileNotFoundError()):\n            return Ok({})\n        case _:\n            return result\n```\n\n#### Printing the Stack Trace\n\nIf you want to format the exception stored in `Err`,\nyou can use `Err.__str__()` and `Err.trace()`.\nThe former will just provide the error message itself\nwhere the latter will provide the entire stack trace.\nThe trace is filtered to remove all intermediate frames for internal functions.\n\nAlso, DrResult overrides the `expecthook` to filter the stack trace in case of panic.\n\n#### `constructs_as_result`\n\nIf you have a class that might raise an error in its constructor,\nyou can mark it as `constructs_as_result`:\n\n```python\n@constructs_as_result\nclass Reader:\n    def __init__(self, filename):\n        with open(filename) as f:\n            self.data = json.loads(f.read())\n```\nCreating an instance of this class will yield a `Result` that has to be unwrapped first.\n```python\nreader = Reader('/path/to/existing/file').unwrap() # Ok\nreader = Reader('/invalid/path/to/non/existing/file').unwrap() # panic!\n```\n\n## Similar Projects\n\nFor a less extreme approach on Rust's result type, see:\n\n* [https://github.com/rustedpy/result](https://github.com/rustedpy/result)\n* [https://github.com/felixhammerl/resultify](https://github.com/felixhammerl/resultify)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": null,
    "version": "0.6.5",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d86a2b3e611fa336134c3b5d5198e69f6a41808921d99a1de5da5a1f7591e49c",
                "md5": "2cf8aa2ae33dee339c0bd725049350a3",
                "sha256": "895a267b8e3a9e77db32d76a43d7cb832cbdf7d213965adecc804bcb7478ebf7"
            },
            "downloads": -1,
            "filename": "drresult-0.6.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2cf8aa2ae33dee339c0bd725049350a3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 11663,
            "upload_time": "2024-10-17T23:51:43",
            "upload_time_iso_8601": "2024-10-17T23:51:43.490233Z",
            "url": "https://files.pythonhosted.org/packages/d8/6a/2b3e611fa336134c3b5d5198e69f6a41808921d99a1de5da5a1f7591e49c/drresult-0.6.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "428c5ba4966ab27d32f424e6aecc13e1149b4772b26dd7d463ed6e8689332922",
                "md5": "660f414264b5c05955c2d4a94288ec49",
                "sha256": "8210d70a7c540a8b0f70e036de4bc7b63554ae145b0586821bfa1c32033724a6"
            },
            "downloads": -1,
            "filename": "drresult-0.6.5.tar.gz",
            "has_sig": false,
            "md5_digest": "660f414264b5c05955c2d4a94288ec49",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 11362,
            "upload_time": "2024-10-17T23:51:45",
            "upload_time_iso_8601": "2024-10-17T23:51:45.568443Z",
            "url": "https://files.pythonhosted.org/packages/42/8c/5ba4966ab27d32f424e6aecc13e1149b4772b26dd7d463ed6e8689332922/drresult-0.6.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-17 23:51:45",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "drresult"
}
        
Elapsed time: 0.33047s