pyella


Namepyella JSON
Version 3.0.1 PyPI version JSON
download
home_pagehttps://pyella.readthedocs.io
SummaryThis library brings common monads such as `Maybe` and `Either` to your Python projects
upload_time2023-09-21 11:36:19
maintainerEly Deckers
docs_urlNone
authorEly Deckers
requires_python>=3.8
licenseMPL-2.0
keywords monad fp maybe either
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Pyella

[![License: MPL 2.0](https://img.shields.io/badge/License-MPL%202.0-brightgreen.svg)](https://opensource.org/licenses/MPL-2.0)
[![Build](https://github.com/edeckers/pyella/actions/workflows/test.yml/badge.svg?branch=develop)](https://github.com/edeckers/pyella/actions/workflows/test.yml)
[![PyPI](https://img.shields.io/pypi/v/pyella.svg?maxAge=3600)](https://pypi.org/project/pyella)
[![security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)

The Pyella library brings common monads such as [Maybe](https://hackage.haskell.org/package/base/docs/Data-Maybe.html) and [Either](https://hackage.haskell.org/package/base/docs/Data-Either.html) to your Python projects.

These monad implementations are strongly inspired by their Haskell namesakes.

## Requirements

- Python 3.8+

## Installation

```bash
pip3 install pyella
```

## Rationale

Some of the main reasons for writing Pyella were:
- I prefer the more explicit error handling `Eithers` can bring compared to regular Exception handling
- Whenever one of my applications crashes due to an NPE, which are almost always avoidable, I die a little inside. `Maybe` can help with that
- A nice chain of `fmaps`, `binds`, et al looks satisfying to me

By no means am I claiming that this library will prevent all NPEs nor that it will prevent any other errors being thrown, because that's not how Python works. It _does_ however make you think more about what states your application can end up in and how you want to handle them, in my experience.

Also consider the cons though, some of which are outlined pretty nicely in this blogpost that deems _Result types_ such as `Either` [leaky abstractions](https://eiriktsarpalis.wordpress.com/2017/02/19/youre-better-off-using-exceptions/). A very valid point! No reason to ditch them altogether, but defintely a warning to use them wisely.

## The name

It's a nod to Python and sounds like [paella](https://en.wikipedia.org/wiki/Paella) ...that's the intention anyway. Seemed somewhat funny to me at the time and that's pretty much all there is to it.

There's no connection to the actual purpose of the library :)

## Usage

### Maybe

The Maybe type represents values that might or might not have a value, and can in many ways be considered the exact same thing as an `Optional`. It brings some extra functionality though, such as mapping, binding and chaining.

A real-world like example for applying `Maybe` would be reading settings from a config file

```python
from pyella.maybe import Maybe

# Let's say we have a trivial configuration loader function
def load_config(path_to_config:Path) -> Dict[str, Any]:
    with open(path_to_config, "r") as config_handle:
       return json.load(config_handle)

# And assume the config file content looks like this
# {
#   "url": "https://api.github.com/repos/edeckers/pyella"
# }

# We'll build upon this `config_json` variable in the
# examples below
config_json = load_config("/path/to/your.conf.json")
```

Say you want to read the `url` setting

```python
maybe_url = Maybe.of(config_json.get("url"))
print (maybe_url)

# Output:
#
# Just("https://api.github.com/repos/edeckers/pyella")
```

And next the 'api_key'

```python
maybe_api_key = Maybe.of(config_json.get("api_key"))
print (maybe_api_key)

# Output:
#
# Nothing
```

Maybe (!) you want to fallback to another value when the `api_key` is missing from the configuration, let's say to an environment variable

```python
api_key = maybe_api_key.from_maybe(os.getenv("MY_API_KEY"))
print (api_key)

# Output:
#
# <a string representing the api key>
```

And for some more trivial examples

```python
j0 = Maybe.of(1)
print (j0)
# Output: Just(1)

print (j0.from_maybe(-1))
# Output: 1

j1 = j0.fmap(lambda x:x*2)
print(j0)
print(j1)
# Output:
#
# Just(1)
# Just(2)
```

### Either

Eithers represent values with two possibilities, often an error and success state. It's convention to use `Left` for the error state and `Right` for the success - or the _right_ - state.

A real-world like example for applying `Either` would be the retrieval of a url, something that might _either_ fail or succeed.

```python
from pyella.either import Either, left, lefts, right, rights

# Let's define a very trivial url retriever which returns a
# `Left<int>` or `Right<Response>` depending on the status code
def fetch_some_interesting_url() -> Either[int, Response]:
    response = request.get("https://api.github.com/repos/edeckers/pyella")

    return Either.pure(response) \
        if response.status_code == 200 else \
            left(response.status_code)

# We'll build upon this `error_or_response` variable in the
# examples below
error_or_response = fetch_some_interesting_url()
```

Maybe you want to print the status code

```python
status_code = error_or_response.if_right(200)
print ("Status code", status_code)

# Output:
#
# Status code <status code>
```

Or maybe you're looking for the occurence of a particular string in the response

```python
is_my_string_there = \
    error_or_response \
        .fmap(lambda response:"monad" in response.text) \
        .if_left(False)
print("Is my string there?", is_my_string_there)

# Output:
#
# Left: Is my string there? False
# Right: Is my string there? <True or False depending on occurrence>
```

How about parsing a succcesful response?

```python
# Say we define this trivial response parser
def parse_response(response: Response) -> Either[int, dict]:
    try:
        return Either.of(str(response.json()))
    except:
        return left(-1)
    
error_or_parsed_response =
    error_or_response \
        .fmap(parse_response)
print (error_or_parsed_response)
```

Seems like not such a bad idea at first glance, and it works:

```python
# Output
#
# Left: Right(Left(-1))
# Right: Right(Right({ "name": "pyella" }))
```

...but that nesting is a little confusing, unnecessary and reminds me of the

                        P Y R A M I D  O F  D O O M

      https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)


Surely there must be a better way to go about this, and there is!

```python
error_or_parsed_response_with_bind =
    error_or_response.bind(parse_response)
print (error_or_parsed_response_with_bind)
   
# Output
#
# Left: Left(-1)
# Right: Right({ "name": "pyella" })
```

That's better! :)

Of course, the value in `Left` has a different meaning now - it's no longer a status code - which is _less than ideal_. A way to deal with this is to introduce a common `Error` type. 

```python
class Error:
    message: str

class HttpReponseError(Error):
    status: int

class ParseError(Error):
    code: int

def fetch_some_interesting_url() -> Either[HttpResponseError, Response]:
    # Use the same implementation as before, but instead of returning
    # Left(<int>) wrap the <int> in a `HttpResponseError` first

def parse_response(response: Response) -> Either[ParseError, dict]:
    # Use the same implementation as before, but instead of returning
    # Left(<int>) wrap the <int> in a `ParseError` first

# Output
#
# Left: Left(HttpResponseError(<status code>) | ParseError(<parse error code>))
# Right: Right({ "name": "pyella" })
```

But at the end of the day you might not even care about the errors. Pyella's got you covered

```python
maybe_response = error_or_parsed_response.to_optional()
print (maybe_response)

# Output
#
# Left: None
# Right: { "name": "pyella" }
```

Or if you prefer to stay within the Pyella domain

```python
maybe_response = error_or_parsed_response.to_maybe()
print (maybe_response)

# Output
#
# Left: Nothing
# Right: Just({ "name": "pyella" })
```

And these are some other, trivial use cases of `Either`

```python
from pyella.either import Either, left, lefts, right, rights

e0: Either[str, int] = left("invalid value")
print(e0)
# Output: Left(invalid value)

print (e0.if_left(-1))
print (e0.if_right("the value was valid"))
# Output:
#
# -1
# 'invalid value'

e1: Either[str, int] = right(1)
print (e1)
# Output: Right(1)

e2 = e1.fmap(lambda x:x*2)
print(e1)
print(e2)
# Output:
#
# Right(1)
# Right(2)

valid_values = rights([e0, e1, e2])
print (valid_values)
# Output: [1, 2]

chained_result = e1.chain(e2)
# Output:
#
# Right(2)

string_result = \
    e1.either( \
        lambda e:f"FAIL: {e}", \
        lambda v:f"SUCCESS: {v}")

# Output:
#
# SUCCESS: 1
```

## Contributing

See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the  repository and the development workflow.

## Code of Conduct

[Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.

## License

MPL-2.0


            

Raw data

            {
    "_id": null,
    "home_page": "https://pyella.readthedocs.io",
    "name": "pyella",
    "maintainer": "Ely Deckers",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "monad,fp,maybe,either",
    "author": "Ely Deckers",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/2e/19/74ebb294c591360819a530b485892243559ba6dea2b1337ca4619aac41ef/pyella-3.0.1.tar.gz",
    "platform": null,
    "description": "# Pyella\n\n[![License: MPL 2.0](https://img.shields.io/badge/License-MPL%202.0-brightgreen.svg)](https://opensource.org/licenses/MPL-2.0)\n[![Build](https://github.com/edeckers/pyella/actions/workflows/test.yml/badge.svg?branch=develop)](https://github.com/edeckers/pyella/actions/workflows/test.yml)\n[![PyPI](https://img.shields.io/pypi/v/pyella.svg?maxAge=3600)](https://pypi.org/project/pyella)\n[![security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)\n\nThe Pyella library brings common monads such as [Maybe](https://hackage.haskell.org/package/base/docs/Data-Maybe.html) and [Either](https://hackage.haskell.org/package/base/docs/Data-Either.html) to your Python projects.\n\nThese monad implementations are strongly inspired by their Haskell namesakes.\n\n## Requirements\n\n- Python 3.8+\n\n## Installation\n\n```bash\npip3 install pyella\n```\n\n## Rationale\n\nSome of the main reasons for writing Pyella were:\n- I prefer the more explicit error handling `Eithers` can bring compared to regular Exception handling\n- Whenever one of my applications crashes due to an NPE, which are almost always avoidable, I die a little inside. `Maybe` can help with that\n- A nice chain of `fmaps`, `binds`, et al looks satisfying to me\n\nBy no means am I claiming that this library will prevent all NPEs nor that it will prevent any other errors being thrown, because that's not how Python works. It _does_ however make you think more about what states your application can end up in and how you want to handle them, in my experience.\n\nAlso consider the cons though, some of which are outlined pretty nicely in this blogpost that deems _Result types_ such as `Either` [leaky abstractions](https://eiriktsarpalis.wordpress.com/2017/02/19/youre-better-off-using-exceptions/). A very valid point! No reason to ditch them altogether, but defintely a warning to use them wisely.\n\n## The name\n\nIt's a nod to Python and sounds like [paella](https://en.wikipedia.org/wiki/Paella) ...that's the intention anyway. Seemed somewhat funny to me at the time and that's pretty much all there is to it.\n\nThere's no connection to the actual purpose of the library :)\n\n## Usage\n\n### Maybe\n\nThe Maybe type represents values that might or might not have a value, and can in many ways be considered the exact same thing as an `Optional`. It brings some extra functionality though, such as mapping, binding and chaining.\n\nA real-world like example for applying `Maybe` would be reading settings from a config file\n\n```python\nfrom pyella.maybe import Maybe\n\n# Let's say we have a trivial configuration loader function\ndef load_config(path_to_config:Path) -> Dict[str, Any]:\n    with open(path_to_config, \"r\") as config_handle:\n       return json.load(config_handle)\n\n# And assume the config file content looks like this\n# {\n#   \"url\": \"https://api.github.com/repos/edeckers/pyella\"\n# }\n\n# We'll build upon this `config_json` variable in the\n# examples below\nconfig_json = load_config(\"/path/to/your.conf.json\")\n```\n\nSay you want to read the `url` setting\n\n```python\nmaybe_url = Maybe.of(config_json.get(\"url\"))\nprint (maybe_url)\n\n# Output:\n#\n# Just(\"https://api.github.com/repos/edeckers/pyella\")\n```\n\nAnd next the 'api_key'\n\n```python\nmaybe_api_key = Maybe.of(config_json.get(\"api_key\"))\nprint (maybe_api_key)\n\n# Output:\n#\n# Nothing\n```\n\nMaybe (!) you want to fallback to another value when the `api_key` is missing from the configuration, let's say to an environment variable\n\n```python\napi_key = maybe_api_key.from_maybe(os.getenv(\"MY_API_KEY\"))\nprint (api_key)\n\n# Output:\n#\n# <a string representing the api key>\n```\n\nAnd for some more trivial examples\n\n```python\nj0 = Maybe.of(1)\nprint (j0)\n# Output: Just(1)\n\nprint (j0.from_maybe(-1))\n# Output: 1\n\nj1 = j0.fmap(lambda x:x*2)\nprint(j0)\nprint(j1)\n# Output:\n#\n# Just(1)\n# Just(2)\n```\n\n### Either\n\nEithers represent values with two possibilities, often an error and success state. It's convention to use `Left` for the error state and `Right` for the success - or the _right_ - state.\n\nA real-world like example for applying `Either` would be the retrieval of a url, something that might _either_ fail or succeed.\n\n```python\nfrom pyella.either import Either, left, lefts, right, rights\n\n# Let's define a very trivial url retriever which returns a\n# `Left<int>` or `Right<Response>` depending on the status code\ndef fetch_some_interesting_url() -> Either[int, Response]:\n    response = request.get(\"https://api.github.com/repos/edeckers/pyella\")\n\n    return Either.pure(response) \\\n        if response.status_code == 200 else \\\n            left(response.status_code)\n\n# We'll build upon this `error_or_response` variable in the\n# examples below\nerror_or_response = fetch_some_interesting_url()\n```\n\nMaybe you want to print the status code\n\n```python\nstatus_code = error_or_response.if_right(200)\nprint (\"Status code\", status_code)\n\n# Output:\n#\n# Status code <status code>\n```\n\nOr maybe you're looking for the occurence of a particular string in the response\n\n```python\nis_my_string_there = \\\n    error_or_response \\\n        .fmap(lambda response:\"monad\" in response.text) \\\n        .if_left(False)\nprint(\"Is my string there?\", is_my_string_there)\n\n# Output:\n#\n# Left: Is my string there? False\n# Right: Is my string there? <True or False depending on occurrence>\n```\n\nHow about parsing a succcesful response?\n\n```python\n# Say we define this trivial response parser\ndef parse_response(response: Response) -> Either[int, dict]:\n    try:\n        return Either.of(str(response.json()))\n    except:\n        return left(-1)\n    \nerror_or_parsed_response =\n    error_or_response \\\n        .fmap(parse_response)\nprint (error_or_parsed_response)\n```\n\nSeems like not such a bad idea at first glance, and it works:\n\n```python\n# Output\n#\n# Left: Right(Left(-1))\n# Right: Right(Right({ \"name\": \"pyella\" }))\n```\n\n...but that nesting is a little confusing, unnecessary and reminds me of the\n\n                        P Y R A M I D  O F  D O O M\n\n      https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)\n\n\nSurely there must be a better way to go about this, and there is!\n\n```python\nerror_or_parsed_response_with_bind =\n    error_or_response.bind(parse_response)\nprint (error_or_parsed_response_with_bind)\n   \n# Output\n#\n# Left: Left(-1)\n# Right: Right({ \"name\": \"pyella\" })\n```\n\nThat's better! :)\n\nOf course, the value in `Left` has a different meaning now - it's no longer a status code - which is _less than ideal_. A way to deal with this is to introduce a common `Error` type. \n\n```python\nclass Error:\n    message: str\n\nclass HttpReponseError(Error):\n    status: int\n\nclass ParseError(Error):\n    code: int\n\ndef fetch_some_interesting_url() -> Either[HttpResponseError, Response]:\n    # Use the same implementation as before, but instead of returning\n    # Left(<int>) wrap the <int> in a `HttpResponseError` first\n\ndef parse_response(response: Response) -> Either[ParseError, dict]:\n    # Use the same implementation as before, but instead of returning\n    # Left(<int>) wrap the <int> in a `ParseError` first\n\n# Output\n#\n# Left: Left(HttpResponseError(<status code>) | ParseError(<parse error code>))\n# Right: Right({ \"name\": \"pyella\" })\n```\n\nBut at the end of the day you might not even care about the errors. Pyella's got you covered\n\n```python\nmaybe_response = error_or_parsed_response.to_optional()\nprint (maybe_response)\n\n# Output\n#\n# Left: None\n# Right: { \"name\": \"pyella\" }\n```\n\nOr if you prefer to stay within the Pyella domain\n\n```python\nmaybe_response = error_or_parsed_response.to_maybe()\nprint (maybe_response)\n\n# Output\n#\n# Left: Nothing\n# Right: Just({ \"name\": \"pyella\" })\n```\n\nAnd these are some other, trivial use cases of `Either`\n\n```python\nfrom pyella.either import Either, left, lefts, right, rights\n\ne0: Either[str, int] = left(\"invalid value\")\nprint(e0)\n# Output: Left(invalid value)\n\nprint (e0.if_left(-1))\nprint (e0.if_right(\"the value was valid\"))\n# Output:\n#\n# -1\n# 'invalid value'\n\ne1: Either[str, int] = right(1)\nprint (e1)\n# Output: Right(1)\n\ne2 = e1.fmap(lambda x:x*2)\nprint(e1)\nprint(e2)\n# Output:\n#\n# Right(1)\n# Right(2)\n\nvalid_values = rights([e0, e1, e2])\nprint (valid_values)\n# Output: [1, 2]\n\nchained_result = e1.chain(e2)\n# Output:\n#\n# Right(2)\n\nstring_result = \\\n    e1.either( \\\n        lambda e:f\"FAIL: {e}\", \\\n        lambda v:f\"SUCCESS: {v}\")\n\n# Output:\n#\n# SUCCESS: 1\n```\n\n## Contributing\n\nSee the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the  repository and the development workflow.\n\n## Code of Conduct\n\n[Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.\n\n## License\n\nMPL-2.0\n\n",
    "bugtrack_url": null,
    "license": "MPL-2.0",
    "summary": "This library brings common monads such as `Maybe` and `Either` to your Python projects",
    "version": "3.0.1",
    "project_urls": {
        "Documentation": "https://github.com/edeckers/pyella",
        "Homepage": "https://pyella.readthedocs.io",
        "Repository": "https://github.com/edeckers/pyella.git"
    },
    "split_keywords": [
        "monad",
        "fp",
        "maybe",
        "either"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3845ad3143e41f9c66f12c968111e2be86706dafb5badcbfdf7b48fb3f54b03c",
                "md5": "3bea8941ec1be340d08015546fffb3a7",
                "sha256": "f57804363b9360f3db893aa0f941a72ea0c514398d10d65af55b199aabd99836"
            },
            "downloads": -1,
            "filename": "pyella-3.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3bea8941ec1be340d08015546fffb3a7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 21163,
            "upload_time": "2023-09-21T11:36:18",
            "upload_time_iso_8601": "2023-09-21T11:36:18.001491Z",
            "url": "https://files.pythonhosted.org/packages/38/45/ad3143e41f9c66f12c968111e2be86706dafb5badcbfdf7b48fb3f54b03c/pyella-3.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2e1974ebb294c591360819a530b485892243559ba6dea2b1337ca4619aac41ef",
                "md5": "2d49ac85b1cf798ab26792749d59c984",
                "sha256": "2732f5d06442d9eee441464e8e1a37cb2b54da4dd17d05ae4efe270b92c25804"
            },
            "downloads": -1,
            "filename": "pyella-3.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "2d49ac85b1cf798ab26792749d59c984",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 16868,
            "upload_time": "2023-09-21T11:36:19",
            "upload_time_iso_8601": "2023-09-21T11:36:19.416227Z",
            "url": "https://files.pythonhosted.org/packages/2e/19/74ebb294c591360819a530b485892243559ba6dea2b1337ca4619aac41ef/pyella-3.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-09-21 11:36:19",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "edeckers",
    "github_project": "pyella",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pyella"
}
        
Elapsed time: 0.12403s