# 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
```sh
pip3 install unless-handler
```
# Usage
> **💡 Remember**
>
>`Result` class has 2 properties and 1 method,
> - Properties
> - `value` - The return value of the function
> - `error` - 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 the `value`
- **Import the `Result` class and `traceback.format_exc` for tracebacks**
```py
from unless.result import Result
from traceback import format_exc # Optional
```
- **Integrate `Result` into your function**
- Initialize the `Result` class (specify the return type for type hints)
```py
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 and `Result()` works too.
- Set the return value
- Use `value` property of the `Result` class to set return value
```py
# <initialized>.value = <value to return>
to_return.value = [1, 2, 3]
```
- Catch and set errors
- Use `error` property of the `Result` class 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
```py
try:
...
except Exception as e:
# <initialized>.error = <exception type>, <traceback.format_exc()>
to_return.error = type(e), format_exc()
```
- Return the result
```py
return to_return
```
- **Calling your function**
- See result using the `value` property
```py
called = my_function()
called.value
```
- See error using the `error` property
```py
called.error
```
- Or better yet, use the `unless` method
```py
called = my_function().unless()
# called is now called.value and errors are handled using handler function
# for more info check "Examples"
```
# Examples
- [Basic usage](#basic-usage)
- [Custom error handler](#custom-error-handling)
- [Integrate with existing functions](#integrate-with-existing-functions)
### Basic usage
```py
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 `unless` method
- Your handler function _must_ accept at least 1 argument
- If you're using `Result.from_func` or following the recommended syntax, the 1st argument will be a tuple consist of `<type of exception>, <traceback string>`
- Handler function _can have_ keyword arguments (`x.unless(func, arg1="first", arg2="second")`)
```py
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,
```py
@Result.from_func
def older(n) -> list:
return [1, 2, 3, n]
```
- As a function,
```py
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
```
Raw data
{
"_id": null,
"home_page": "https://github.com/Itz-fork/Unless",
"name": "unless-handler",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.6",
"maintainer_email": "",
"keywords": "unless,error-handler,simplified,error,python-error-handler",
"author": "Itz-fork",
"author_email": "git.itzfork@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/67/a1/8eb75dbda1ec4e28bcbc66e54da0f67f1c72d098dcb35591cb3772f102ef/unless-handler-0.2.tar.gz",
"platform": null,
"description": "# Unless\n**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.\n\n\n# Install\n```sh\npip3 install unless-handler\n```\n\n\n# Usage\n> **\ud83d\udca1 Remember**\n>\n>`Result` class has 2 properties and 1 method,\n> - Properties\n> - `value` - The return value of the function\n> - `error` - Information about the error if there was any\n> - It can be either a tuple of the exception type and traceback string, or just the traceback string\n>\n> - Methods\n> - `unless` - Handle errors and return the `value`\n\n\n- **Import the `Result` class and `traceback.format_exc` for tracebacks**\n ```py\n from unless.result import Result\n\n from traceback import format_exc # Optional\n ```\n\n\n- **Integrate `Result` into your function**\n - Initialize the `Result` class (specify the return type for type hints)\n ```py\n def cool():\n to_return = Result[list]()\n ^\n Return type\n ```\n > `[list]` is the return type of the function and is there so we can have type hints. It is OPTIONAL and `Result()` works too.\n\n\n - Set the return value\n - Use `value` property of the `Result` class to set return value\n ```py\n # <initialized>.value = <value to return>\n to_return.value = [1, 2, 3]\n ```\n\n - Catch and set errors\n - Use `error` property of the `Result` class to set errors\n - 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\n ```py\n try:\n ...\n except Exception as e:\n # <initialized>.error = <exception type>, <traceback.format_exc()>\n to_return.error = type(e), format_exc()\n ```\n\n - Return the result\n ```py\n return to_return\n ```\n\n- **Calling your function**\n - See result using the `value` property\n ```py\n called = my_function()\n\n called.value\n ```\n \n - See error using the `error` property\n ```py\n called.error\n ```\n \n - Or better yet, use the `unless` method\n ```py\n called = my_function().unless()\n\n # called is now called.value and errors are handled using handler function\n # for more info check \"Examples\"\n ```\n\n\n# Examples\n- [Basic usage](#basic-usage)\n- [Custom error handler](#custom-error-handling)\n- [Integrate with existing functions](#integrate-with-existing-functions)\n\n\n### Basic usage\n```py\ndef cool():\n to_return = Result[list]()\n try:\n to_return.value = [1, 2, 3]\n raise ValueError(\"Annoying error...\")\n except Exception as e:\n to_return.error = type(e), traceback.format_exc()\n return to_return\n\n# Calling the function\nx = cool().unless()\nprint(x)\n```\n\n### Custom error handling\nYou can call functions with custom error handling logic using `Result.unless` method that your function returns.\n\n- You can pass **any python function** to the `unless` method\n- Your handler function _must_ accept at least 1 argument\n - If you're using `Result.from_func` or following the recommended syntax, the 1st argument will be a tuple consist of `<type of exception>, <traceback string>`\n- Handler function _can have_ keyword arguments (`x.unless(func, arg1=\"first\", arg2=\"second\")`)\n\n```py\ndef custom_handler(e, notes):\n _, fmt_traceback = e\n logging.warn(f\"{fmt_traceback} \\n\\nNotes: {notes}\")\n\nx = cool().unless(\n custom_handler,\n notes=\"Probably happend because the function was hot\"\n )\nprint(x)\n```\n\n### Integrate with existing functions\nYou can use `Result.from_func` method to integrate this with existing functions.\n\n- As a decorator,\n ```py\n @Result.from_func\n def older(n) -> list:\n return [1, 2, 3, n]\n ```\n- As a function,\n ```py\n def older(n) -> list:\n return [1, 2, 3, n]\n\n x = Result.from_func(older, list, n=2)\n\n # Important:\n # if your function doesn't accept arguments, use \"()\" at the end to call it properly\n \n # Example:\n x = Result.from_func(no_args)()\n ^\n Call the function\n ```\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Lightweight python library for error handling",
"version": "0.2",
"project_urls": {
"Download": "https://github.com/Itz-fork/Unless/archive/refs/tags/v0.2.tar.gz",
"Homepage": "https://github.com/Itz-fork/Unless"
},
"split_keywords": [
"unless",
"error-handler",
"simplified",
"error",
"python-error-handler"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "67a18eb75dbda1ec4e28bcbc66e54da0f67f1c72d098dcb35591cb3772f102ef",
"md5": "239d0f715d46e8355a7caa2535dbda20",
"sha256": "01f5438e1e945e43f1f55ed1de2dcde2b4db8fcaeef67ffb57ea357f3c3525d2"
},
"downloads": -1,
"filename": "unless-handler-0.2.tar.gz",
"has_sig": false,
"md5_digest": "239d0f715d46e8355a7caa2535dbda20",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.6",
"size": 4942,
"upload_time": "2024-01-16T16:51:13",
"upload_time_iso_8601": "2024-01-16T16:51:13.848160Z",
"url": "https://files.pythonhosted.org/packages/67/a1/8eb75dbda1ec4e28bcbc66e54da0f67f1c72d098dcb35591cb3772f102ef/unless-handler-0.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-01-16 16:51:13",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Itz-fork",
"github_project": "Unless",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "unless-handler"
}