Skip to main content

with-err

with-err is a python library that converts try-except pattern into Go-like result, err pattern. I feel result, err pattern easier to maintain in large projects.

Getting Started

Install

pip install with-err

(with uv)

uv pip install with-err

Use as Function

import json
from with_err import with_err

json_loads_e = with_err(json.loads)

data, err = json_loads_e('{"a": 1}')
assert err is None
assert data == {"a": 1}

data, err = json_loads_e('{"a": }')
assert isinstance(err, json.decoder.JSONDecodeError)
assert data is None

Use as Decorator

import json
from with_err import with_err

@with_err
def json_loads_e(a: str):
    return json.loads(a)

data, err = json_loads_e('{"a": 1}')
assert err is None
assert data == {"a": 1}

data, err = json_loads_e('{"a": }')
assert isinstance(err, json.decoder.JSONDecodeError)
assert data is None

with_exc with Specified Exceptions

Return err only with specified exceptions and raise other exceptions.

import json
from with_err import with_exc

@with_exc(json.decoder.JSONDecodeError)
def json_loads_e(a: str):
    return json.loads(a)

data, err = json_loads_e('{"a": 1}')
assert err is None
assert data == {"a": 1}

data, err = json_loads_e('{"a": }')
assert isinstance(err, json.decoder.JSONDecodeError)
assert data is None
# raise json.decoder.JSONDecodeError

import json
import re
from with_err import with_err

@with_exc(re.PatternError)
def json_loads_e(a: str):
    return json.loads(a)

data, err = json_loads_e('{"a": }')
# function

import json
from with_err import with_exc

json_loads_e = with_exc(json.decoder.JSONDecodeError)(json.loads)

data, err = json_loads_e('{"a": 1}')
assert err is None
assert data == {"a": 1}

data, err = json_loads_e('{"a": }')
assert isinstance(err, json.decoder.JSONDecodeError)
assert data is None
# empty: return all Exceptions

import json
from with_err import with_exc

json_loads_e = with_exc()(json.loads)

data, err = json_loads_e('{"a": 1}')
assert err is None
assert data == {"a": 1}

data, err = json_loads_e('{"a": }')
assert isinstance(err, json.decoder.JSONDecodeError)
assert data is None

Async Functions

from with_err import with_async_err

async def async_fetch_data(endpoint: str) -> dict[str, str]:
    if endpoint == "bad":
        raise ValueError("Failed to reach endpoint")
    return {"status": "ok"}

async_fetch_data_e = with_async_err(async_fetch_data)
res, err = await async_fetch_data_e("bad")
assert isinstance(err, ValueError)
assert res is None

Generators

from with_err import with_gen_err


@with_gen_err
def my_stream():
    yield 1
    raise ValueError('invalid')

for idx, (each, err) in enumerate(my_stream()):
    if idx == 0:
        assert each == 1
        assert err is None
    else:
        assert each is None
        assert isinstance(err, ValueError)

Async Generators

from with_err import with_async_gen_err


@with_async_gen_err
async def my_async_stream():
    yield 1
    raise ValueError('invalid')

async for each, err in my_async_stream():
    if each == 1:
        assert each == 1
        assert err is None
    else:
        assert each is None
        assert isinstance(err, ValueError)

Functions Returning list or tuple

@with_err
def my_list_func(is_good=False):
    if not is_good:
        raise ValueError('not good')
    return [1, 2]

data, err = my_list_func()
assert data is None
assert isinstance(err, ValueError)

data, err = my_list_func(True)
assert data is not None
assert err is None
item1, item2 = data
assert item1 == 1
assert item2 == 2

Get err Traceback Stack

import json
from with_err import with_err, get_err_strs


@with_err
def json_loads_e(a: str):
    return json.loads(a)

_data, err = json_loads_e('{"a": 1}')
err_stack = get_err_strs(err)
assert err is None
assert err_stack == []
import json
import re
from with_err import with_err, get_err_strs


@with_err
def json_loads_e(a: str):
    return json.loads(a)

_data, err = json_loads_e('{"a": }')
err_stack = get_err_strs(err)
err_str = '\n'.join(err_stack)
assert isinstance(err, json.decoder.JSONDecodeError)
assert len(err_stack) > 0
assert re.search(r', line \d+, in json_loads_e', err_str)
assert re.search(r'json/__init__.py", line \d+, in loads', err_str)
assert 'json.decoder.JSONDecodeError: Expecting value:' in err_str
import json
import re
from with_err import with_err, get_err_strs, raise_err


@with_err
def json_loads_e(a: str):
    return json.loads(a)


@with_err
def gen_err():
    data, err = json_loads_e('{"a": }')
    if err is not None:
        raise err
    return data

data, err = gen_err()
err_stack = get_err_strs(err)
err_str = '\n'.join(err_stack)
assert isinstance(err, json.decoder.JSONDecodeError)
assert len(err_stack) > 0
assert re.search(r', line \d+, in gen_err', err_str)
assert re.search(r', line \d+, in json_loads_e', err_str)
assert re.search(r'json/__init__.py", line \d+, in loads', err_str)
assert 'json.decoder.JSONDecodeError: Expecting value:' in err_str

Raise err

import json
import re
from with_err import with_err, get_err_strs, raise_err


@with_err
def json_loads_e(a: str):
    return json.loads(a)

def gen_err():
    data, err = json_loads_e('{"a": }')
    return data, raise_err(err)

data, err = gen_err()
err_stack = get_err_strs(err)
err_str = '\n'.join(err_stack)
assert isinstance(err, json.decoder.JSONDecodeError)
assert len(err_stack) > 0
assert re.search(r', line \d+, in gen_err', err_str)
assert re.search(r', line \d+, in json_loads_e', err_str)
assert re.search(r'json/__init__.py", line \d+, in loads', err_str)
assert 'json.decoder.JSONDecodeError: Expecting value:' in err_str

Iterables

@with_err
def echo_e(a: str):
    return a


def test_get_results():
    strs = [r'[0-9', r'\d+', r'\W+', r'\d+\W+', r'[z-a]', r'\d+\W*']

    rets = [echo_e(each) for each in strs]

    errs = get_errs(rets)
    assert len(errs) == 6
    assert errs[0] is None
    assert errs[1] is None
    assert errs[2] is None
    assert errs[3] is None
    assert errs[4] is None
    assert errs[5] is None

    first_err = get_first_err(rets)
    assert first_err is None

    the_is_any_err = is_any_err(rets)
    assert not the_is_any_err

    the_is_all_err = is_all_err(rets)
    assert not the_is_all_err

    results = get_results(rets)
    assert len(results) == 6
    assert results[0] == r'[0-9'
    assert results[1] == r'\d+'
    assert results[2] == r'\W+'
    assert results[3] == r'\d+\W+'
    assert results[4] == r'[z-a]'
    assert results[5] == r'\d+\W*'

    results = get_results_or_none(rets)
    assert len(results) == 6
    assert results[0] == r'[0-9'
    assert results[1] == r'\d+'
    assert results[2] == r'\W+'
    assert results[3] == r'\d+\W+'
    assert results[4] == r'[z-a]'
    assert results[5] == r'\d+\W*'

Acknowledgement

The implementation is based on the following Gemini / ChatGPT suggestions:

Metadata

Release files for with-err 1.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for with-err 1.4.0
File Size Uploaded Provenance Actions
with_err-1.4.0.tar.gz 5.1 kB Without provenance Details for with_err-1.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for with-err 1.4.0
File Interpreter ABI Platform Actions
with_err-1.4.0-py3-none-any.whl Python 3 none any Details for with_err-1.4.0-py3-none-any.whl

Total release size: 11.2 kB

Release files / with_err-1.4.0.tar.gz

Download URL with_err-1.4.0.tar.gz
Size 5.1 kB
Tags Source
SHA-256 checksum
How to use checksums
fd4f66a024c78dc52f47f3056eb52e11bffeeb9c26f52e95791ea5798021c244
BLAKE2b-256 checksum
How to use checksums
11674fce65f4f88461aa1506ab6e7798d7bf0af71d18dd2386f777eebe1c6c5b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / with_err-1.4.0-py3-none-any.whl

Download URL with_err-1.4.0-py3-none-any.whl
Size 6.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
aea33e365d261873ce6afd4eb33b7064ba04715687109ed61736ea2631f1ef55
BLAKE2b-256 checksum
How to use checksums
a15f443d8004bc592f6b0eebfea28c70dd303bde7719e650eb99c4dcb789bd57
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for with-err 1.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page