Unless
Unless is a lightweight python library designed to simplify error handling. It introduces the Result class that encapsulates the result of a function call, which can be either the return value, an error, or both.
Install
pip3 install unless-handler
Usage
💡 Remember
Resultclass has 2 properties and 1 method,
Properties
value- The return value of the functionerror- Information about the error if there was any
- It can be either a tuple of the exception type and traceback string, or just the traceback string
Methods
unless- Handle errors and return thevalue
-
Import the
Resultclass andtraceback.format_excfor tracebacksfrom unless.result import Result from traceback import format_exc # Optional
-
Integrate
Resultinto your function-
Initialize the
Resultclass (specify the return type for type hints)def cool(): to_return = Result[list]() ^ Return type
[list]is the return type of the function and is there so we can have type hints. It is OPTIONAL andResult()works too. -
Set the return value
- Use
valueproperty of theResultclass to set return value
# <initialized>.value = <value to return> to_return.value = [1, 2, 3]
- Use
-
Catch and set errors
- Use
errorproperty of theResultclass to set errors - You have the freedom to set any value you like; however, it is recommended to follow the given syntax of
<type>, <traceback>as it gives the ability to have caused exception type and the traceback for better error handling
try: ... except Exception as e: # <initialized>.error = <exception type>, <traceback.format_exc()> to_return.error = type(e), format_exc()
- Use
-
Return the result
return to_return
-
-
Calling your function
-
See result using the
valuepropertycalled = my_function() called.value
-
See error using the
errorpropertycalled.error
-
Or better yet, use the
unlessmethodcalled = my_function().unless() # called is now called.value and errors are handled using handler function # for more info check "Examples"
-
Examples
Basic usage
def cool():
to_return = Result[list]()
try:
to_return.value = [1, 2, 3]
raise ValueError("Annoying error...")
except Exception as e:
to_return.error = type(e), traceback.format_exc()
return to_return
# Calling the function
x = cool().unless()
print(x)
Custom error handling
You can call functions with custom error handling logic using Result.unless method that your function returns.
- You can pass any python function to the
unlessmethod - Your handler function must accept at least 1 argument
- If you're using
Result.from_funcor following the recommended syntax, the 1st argument will be a tuple consist of<type of exception>, <traceback string>
- If you're using
- Handler function can have keyword arguments (
x.unless(func, arg1="first", arg2="second"))
def custom_handler(e, notes):
_, fmt_traceback = e
logging.warn(f"{fmt_traceback} \n\nNotes: {notes}")
x = cool().unless(
custom_handler,
notes="Probably happend because the function was hot"
)
print(x)
Integrate with existing functions
You can use Result.from_func method to integrate this with existing functions.
- As a decorator,
@Result.from_func def older(n) -> list: return [1, 2, 3, n]
- As a function,
def older(n) -> list: return [1, 2, 3, n] x = Result.from_func(older, list, n=2) # Important: # if your function doesn't accept arguments, use "()" at the end to call it properly # Example: x = Result.from_func(no_args)() ^ Call the function
Metadata
Release files for unless-handler 0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| unless-handler-0.2.tar.gz | 4.9 kB | Without provenance | Details for unless-handler-0.2.tar.gz |
Release files / unless-handler-0.2.tar.gz
| Download URL | unless-handler-0.2.tar.gz |
|---|---|
| Size | 4.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
01f5438e1e945e43f1f55ed1de2dcde2b4db8fcaeef67ffb57ea357f3c3525d2
|
|
BLAKE2b-256 checksum How to use checksums |
67a18eb75dbda1ec4e28bcbc66e54da0f67f1c72d098dcb35591cb3772f102ef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/4.0.2 CPython/3.11.6
|
Security for unless-handler 0.2
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.