{"id":17807476,"url":"https://github.com/zero323/tryingsnake","last_synced_at":"2025-03-17T13:31:30.172Z","repository":{"id":45851956,"uuid":"45198172","full_name":"zero323/tryingsnake","owner":"zero323","description":"Exception handling, the functional way.","archived":false,"fork":false,"pushed_at":"2022-02-10T15:58:31.000Z","size":114,"stargazers_count":9,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-28T00:36:28.514Z","etag":null,"topics":["exception-handler","functional-programming","python","try"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zero323.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":null,"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":["https://archive.org/donate","https://supporters.eff.org/donate","https://www.msf.org/donate"]}},"created_at":"2015-10-29T17:07:06.000Z","updated_at":"2024-01-13T23:54:30.000Z","dependencies_parsed_at":"2022-09-04T05:11:33.194Z","dependency_job_id":null,"html_url":"https://github.com/zero323/tryingsnake","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zero323%2Ftryingsnake","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zero323%2Ftryingsnake/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zero323%2Ftryingsnake/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zero323%2Ftryingsnake/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zero323","download_url":"https://codeload.github.com/zero323/tryingsnake/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243864809,"owners_count":20360360,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["exception-handler","functional-programming","python","try"],"created_at":"2024-10-27T14:22:09.291Z","updated_at":"2025-03-17T13:31:29.787Z","avatar_url":"https://github.com/zero323.png","language":"Python","readme":"TryingSnake\n===========\n[![Tests Status](https://github.com/zero323/tryingsnake/actions/workflows/test.yml/badge.svg)](https://github.com/zero323/tryingsnake/actions/workflows/test.yml)\n[![Code\nClimate](https://codeclimate.com/github/zero323/tryingsnake/badges/gpa.svg)](https://codeclimate.com/github/zero323/tryingsnake)\n[![GitHub release (latest by date)](https://img.shields.io/github/v/release/zero323/tryingsnake)](https://github.com/zero323/tryingsnake/releases/latest)\n[![PyPI](https://img.shields.io/pypi/v/tryingsnake?color=blue)](https://pypi.org/project/tryingsnake/)\n[![Conda Version](https://img.shields.io/conda/vn/conda-forge/tryingsnake.svg?color=blue)](https://anaconda.org/conda-forge/tryingsnake)\n[![License\nMIT](https://img.shields.io/pypi/l/tryingsnake.svg)](https://github.com/zero323/tryingsnake/blob/master/LICENSE)\n\nA simple, `Try` implementation inspired by\n[scala.util.Try](https://www.scala-lang.org/api/current/scala/util/Try.html)\n\nExamples\n========\n\n-   Wrap functions with arguments:\n\n    ```python\n    \u003e\u003e\u003e from tryingsnake import Try, Try_, Success, Failure\n    \u003e\u003e\u003e from operator import add, truediv\n    \u003e\u003e\u003e Try(add, 0, 1)\n    Success(1)\n    \u003e\u003e\u003e Try(truediv, 1, 0)  # doctest:+ELLIPSIS\n    Failure(ZeroDivisionError(...))\n    ```\n\n-   Avoid sentinel values:\n\n    ```python\n    \u003e\u003e\u003e def mean_1(xs):\n    ...     try:\n    ...         return sum(xs) / len(xs)\n    ...     except ZeroDivisionError as e:\n    ...         return float(\"inf\")  # What does it mean?\n    \u003e\u003e\u003e mean_1([])\n    inf\n    ```\n\n    vs.\n\n    ```python\n    \u003e\u003e\u003e def mean_2(xs):\n    ...     return sum(xs) / len(xs)\n    \u003e\u003e\u003e Try(mean_2, [])  # doctest:+ELLIPSIS\n    Failure(ZeroDivisionError(...))\n    \u003e\u003e\u003e Try(mean_2, [\"foo\", \"bar\"])  # doctest:+ELLIPSIS\n    Failure(TypeError(...))\n    ```\n\n-   Follow the happy path:\n\n    ```python\n    \u003e\u003e\u003e def inc(x): return x + 1\n    \u003e\u003e\u003e def inv(x): return 1. / x\n\n    \u003e\u003e\u003e Success(1).map(inc).map(inv)\n    Success(0.5)\n\n    \u003e\u003e\u003e Failure(Exception(\"e\")).map(inc).map(inv)  # doctest:+ELLIPSIS\n    Failure(Exception(...))\n\n    \u003e\u003e\u003e Success(-1).map(inc).map(inv)  # doctest:+ELLIPSIS\n    Failure(ZeroDivisionError(...))\n    ```\n\n-   Recover:\n\n    ```python\n    \u003e\u003e\u003e def get(url):\n    ...     if \"mirror\" in url:\n    ...         raise IOError(\"No address associated with hostname\")\n    ...     return url\n    \u003e\u003e\u003e mirrors = [\"http://mirror1.example.com\", \"http://example.com\"]\n    \u003e\u003e\u003e Try(get, mirrors[0]).recover(lambda _: get(mirrors[1]))\n    Success('http://example.com')\n    ```\n\n-   Let them fail:\n\n    ```python\n    \u003e\u003e\u003e from operator import getitem\n    \u003e\u003e\u003e Try(getitem, [], 0)  # doctest:+ELLIPSIS\n    Failure(IndexError(...))\n    \u003e\u003e\u003e Try_.set_unhandled([IndexError])\n    \u003e\u003e\u003e Try(getitem, [], 0)\n    Traceback (most recent call last):\n        ...\n    IndexError: list index out of range\n    ```\n\n-   Make things (relatively) simple:\n\n    ```python\n    \u003e\u003e\u003e import math\n    \u003e\u003e\u003e xs = [1.0, 0.0, \"-1\", -3, 2, 1 + 2j]\n    \u003e\u003e\u003e sqrts = [Try(math.sqrt, x) for x in xs]\n    \u003e\u003e\u003e [x.get() for x in sqrts if x.isSuccess]\n    [1.0, 0.0, 1.4142135623730951]\n    \u003e\u003e\u003e def get_etype(e):\n    ...     return Try(lambda x: type(x).__name__, e)\n    \u003e\u003e\u003e [x.recoverWith(get_etype).get() for x in sqrts if x.isFailure]\n    ['TypeError', 'ValueError', 'TypeError']\n    ```\n\n-   Inline exception handling:\n\n    ```python\n    \u003e\u003e\u003e from tryingsnake.curried import Try\n    \u003e\u003e\u003e map(Try(str.split), [\"foo bar\", None])  # doctest:+ELLIPSIS\n    \u003cmap at ...\u003e\n    ```\n\n-   Decorate your functions:\n\n    ```python\n    \u003e\u003e\u003e from tryingsnake.curried import Try as try_\n    \u003e\u003e\u003e @try_\n    ... def scale_imag(x):\n    ...     return complex(x.real, x.imag * 2)\n    \u003e\u003e\u003e [scale_imag(x) for x in [1 + 2j, \"3\", 42 + 0j]]\n    [Success((1+4j)), Failure(AttributeError(\"'str' object has no attribute 'real'\")), Success((42+0j))]\n    ```\n\n-   Wrap generator objects:\n\n    ```python\n    \u003e\u003e\u003e def get_nth(xs, i):\n    ...     yield xs[i]\n    \u003e\u003e\u003e xs = [1, 3, 5, 7]\n    \u003e\u003e\u003e Try(get_nth(xs, 3))\n    Success(7)\n    \u003e\u003e\u003e Try(get_nth(xs, 11))\n    Failure(IndexError('list index out of range'))\n    \u003e\u003e\u003e def f():\n    ...     divisor = 1\n    ...     while True:\n    ...         divisor_ = yield 1 / divisor\n    ...         divisor = divisor_ if divisor_ is not None else 1\n    \u003e\u003e\u003e g = f()\n    \u003e\u003e\u003e next(g)  # Should be primed\n    1.0\n    \u003e\u003e\u003e Try(g, 2)\n    Success(0.5)\n    \u003e\u003e\u003e Try(g, 0)\n    Failure(ZeroDivisionError('division by zero'))\n    ```\n\nInstallation\n============\n\nThis package is available on PYPI:\n\n    pip install tryingsnake\n\nand conda-forge:\n\n    conda install -c conda-forge tryingsnake\n\n\nDependencies\n=======\n\n`tryingsnake` supports Python 3.6 or later and\nrequires no external dependencies.\n\nLicense\n=======\n\nMIT, See\n[LICENSE](https://github.com/zero323/tryingsnake/blob/master/LICENSE)\n\nFAQ\n===\n\n-   Q: Is this project production-ready?\n-   A: Sure, for some definition of production-ready. It is a toy project.\n    It has decent test coverage, stable API, and in general seems to do\n    what is expected to do. But it is not widely used, and the API design\n    and overall idea are rather unpythonic.\n-   Q: Why to use mixedCase method names instead of lowercase\n    recommended by PEP8?\n-   A: Mostly to make switching between Python and Scala code as\n    painless as possible.\n-   Q: What is the runtime cost?    \n    A: As of [0088286](https://github.com/zero323/tryingsnake/commit/00882862d655cd3d77ea730449f498883ed584d5) (releases 0.3 and 0.4 suffered from\n    severe performance regression caused by using `typing.Generic` as a base of\n    try. See [#18](https://github.com/zero323/tryingsnake/issues/18) for details)\n    rough numbers for simple tasks look as follows:\n\n    ```\n    Python 3.7.5 (default, Oct 27 2019, 15:43:29)\n    Type 'copyright', 'credits' or 'license' for more information\n    IPython 7.11.0 -- An enhanced Interactive Python. Type '?' for help.\n    In [1]: def identity(x): return x\n    In [2]: from tryingsnake import Try\n    In [3]: %timeit for i in range(1_000_000): identity(i)\n    59.8 ms ± 683 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\n    In [4]: %timeit for i in range(1_000_000): Try(identity, i)\n    408 ms ± 4.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n    ```\n\n    and execution time is dominated by the initializer:\n\n    ```\n    In [5]: import cProfile\n    In [6]: cProfile.run(\"for i in range(1_000_000): Try(identity, i)\")\n             4000003 function calls in 0.961 seconds\n\n       Ordered by: standard name\n\n       ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n      1000000    0.078    0.000    0.078    0.000 \u003cipython-input-1-abafd771428d\u003e:1(identity)\n            1    0.263    0.263    0.961    0.961 \u003cstring\u003e:1(\u003cmodule\u003e)\n      1000000    0.094    0.000    0.094    0.000 __init__.py:234(__init__)\n      1000000    0.480    0.000    0.698    0.000 __init__.py:352(Try)\n      1000000    0.046    0.000    0.046    0.000 {built-in method builtins.callable}\n            1    0.000    0.000    0.961    0.961 {built-in method builtins.exec}\n            1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}\n    ```\n\n    This is quite a lot for simple functions so you should probably avoid it in such cases, where raw performance is important. It is still possible to amortize the cost in such cases, for example using composition:\n\n    ```python\n    from toolz.functoolz import compose\n    from tryingsnake import Try\n\n    Try(compose(str.split, str.lower, str.strip), \" Foo BAR FooBar \")\n    ```\n\n    Memory overhead (as measured by [memory-profiler](https://pypi.org/project/memory-profiler/)) looks as follows:\n\n    ```\n    Line #    Mem usage    Increment   Line Contents\n    ================================================\n     6     37.9 MiB     37.9 MiB   @profile\n     7                             def f():\n     8    155.5 MiB      0.8 MiB       [Try(identity, i) for i in range(1_000_000)]\n    ```\n\n    compared to:\n\n    ```\n    Line #    Mem usage    Increment   Line Contents\n    ================================================\n     6     37.9 MiB     37.9 MiB   @profile\n     7                             def f():\n     8     77.4 MiB      1.0 MiB       [identity(i) for i in range(1_000_000)]\n     ```\n","funding_links":["https://archive.org/donate","https://supporters.eff.org/donate","https://www.msf.org/donate"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzero323%2Ftryingsnake","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzero323%2Ftryingsnake","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzero323%2Ftryingsnake/lists"}