Welcome to aiofunctools’s documentation!¶
Bind¶
Description¶
Function used to pass-through execution if input is an Exception.
In addition, it currify function.
Example¶
def x5(x: int) -> int:
return x * 5
maybe_x5 = bind(x5)
assert maybe_x5(1) == 5
error = maybe_x5(Exception())
Curry¶
Curried functions admit less inputs than mandatory ones and return a function with that inputs fixed.
In this great book is explained better.
def _sum(x: int, y: int) -> int:
return x + y
maybe_sum = bind(_sum)
maybe_sum1 = maybe_sum(1)
assert maybe_sum1(4) == 5
error = maybe_sum1(Exception())
Decorator¶
@bind
def x5(x: int) -> int:
return x * 5
Compose¶
Description¶
Function used to compose other functions.
Allow async functions.
First input function is first executed.
Example¶
Compose:
from aiofunctools import compose
async def test(_input):
return await compose(
first,
awaitable_second,
third)(_input)
It is same code than:
from aiofunctools import compose
async def test(_input):
return third(
await awaitable_second(
first(_input)))
aiofunctools¶
Library to help in Python functional programing. It’s asyncio compatible.
Basic idea behind it is Railway Oriented Programing.
This allows us to:
- simplify our code.
- improve error management.
- be cool! be functional!
Examples:
Old code example:
async def create_user_handler(request) -> Response:
try:
user = check_valid_user(request)
create_user(user)
except InvalidBody:
return_422('Invalid body')
except UserAlreadyExists:
return_409('User already exists')
return_201(user)
ROP example:
async def create_user_handler(request) -> Response:
return await compose(
check_valid_user,
create_user,
return_201
)(request)