Exception handling, the functional way.
Project description
TryingSnake
A simple, Try implementation inspired by scala.util.Try
Examples
Wrap functions with arguments:
>>> from tryingsnake import Try, Success, Failure >>> def succeed(): return 1 >>> Try(succeed) Success(1) >>> def fail(): return 1/ 0 >>> Try(fail) Failure(ZeroDivisionError('integer division or modulo by zero',))
Avoid sentinel values:
>>> def mean_1(xs): ... try: ... return sum(xs) / len(xs) ... except ZeroDivisionError as e: ... return None >>> mean_1([]) # What does it mean?
vs.
>>> def mean_2(xs): return sum(xs) / len(xs) >>> Try(mean_2, []) Failure(ZeroDivisionError('integer division or modulo by zero',)) >>> Try(mean_2, ["foo", "bar"]) Failure(TypeError("unsupported operand type(s) for +: 'int' and 'str'",))
Follow the happy path:
>>> def inc(x): return x + 1 >>> def inv(x): return 1. / x >>> Success(1).map(inc).map(inv) Success(0.5) >>> Failure(Exception("e")).map(inc).map(inv) Failure(Exception('e',)) >>> Success(-1).map(inc).map(inv) Failure(ZeroDivisionError('float division by zero',))
Recover:
>>> import urllib >>> def get(url): return urllib.urlopen(url).url >>> mirrors = ["http://mirror1.example.com", "http://example.com"] >>> Try(get, mirrors[0]).recover(lambda _: get(mirrors[1])) Success('http://example.com')
Let them fail:
>>> from operator import getitem >>> Try(getitem, [], 0) Failure(IndexError('list index out of range',)) >>> Try_.set_unhandled([IndexError]) >>> Try(getitem, [], 0) Traceback (most recent call last): ... IndexError: ...
INSTALLATION
pip install tryingsnake
or
easy_install tryingsnake
LICENSE
MIT, See LICENSE
FAQ
Q: Is this project production-ready?
A: No, and it probablly won’t be.
Q: Why to use mixedCase method names instead of lowercase recommended by PEP8?
A: Mostly to make switching between Python and Scala code as painless as possible.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
tryingsnake-0.2.0.tar.gz
(3.6 kB
view hashes)