Simple Monads for Python. Use Just to end checking for None, Success to end unhandled exceptions, and Reader for dependency injection.
Project description
simplemonads
Simple Monads for Python. Use Just to end checking for None, Success to end unhandled exceptions, and Reader for dependency injection.
Platform support
Works across all platforms on CPython >= 3.5, in browser with Brython, and even on microcontrollers with micropython!
Example using monads: Success
, Failure
, Just
, Reader
, and Printer
from simplemonads import Success, Failure, Just, _, Reader, run, Printer
class AppDeps:
def __init__(self, gui=Printer()):
self.gui = gui
def app(divide_by_zero=False):
data = Success(Just(7))
double = lambda x: x + (lambda y: y * 2)
triple = lambda x: x + (lambda y: y * 3)
result = data + triple + double
if divide_by_zero:
result += (lambda x: x + (lambda x: x / 0))
def effect(deps: AppDeps):
return result | {
Success:lambda x: x | {
Just:lambda val: deps.gui.Popup('Answer to the Universe: ' + str(val))
},
Failure:lambda x: deps.gui.Popup('Whoops, an error happened: ' + x)
} is result or result
return Reader(effect)
class GuiAppDeps(AppDeps):
def __init__(self, gui=Printer()):
try:
import PySimpleGUI
self.gui = PySimpleGUI
except:
self.gui = gui
@run
def main():
return app() + GuiAppDeps
Handling exceptions
To demonstrate exception handling the above example can be changed to:
return app(True) + GuiAppDeps
This will result in safely handling the divide by zero exception and will run the following without interrupting the flow of the application:
Failure:lambda x: deps.gui.Popup('Whoops, an error happened: ' + x)
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
simplemonads-1.0.5.tar.gz
(3.5 kB
view hashes)
Built Distribution
Close
Hashes for simplemonads-1.0.5-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8d7833541ed991a0da7b88f47c01da646e06a75891fe2146581279a641e6abd8 |
|
MD5 | 4148188811bc21f1e90b657d3143b311 |
|
BLAKE2b-256 | eb97a500bb248330740307c24fa9dd5e5730ceed7b5413ea821107987f7993c2 |