Composable Python for production via syntactic sugar
Project description
Why pysweet?
Python can sometimes be unwieldy in production.
Consider the following 3 variants of the same logic:
acc = []
for x in range(10):
y = x + 1
if y % 2 == 0:
acc.extend([y, y * 2])
acc = [
z for y in (x + 1 for x in range(10))
for z in [y, y * 2] if y % 2 == 0
]
from itertools import chain
acc = list(chain.from_iterable(map(
lambda x: [x, x * 2],
filter(
lambda x: x % 2 == 0,
map(lambda x: x + 1, range(10)),
),
)))
The first is in the imperative style; it can become convoluted as requirements evolve.
The second uses comprehensions, which can get complicated when nested.
The last utilizes functional programming: more modular, but not as readable.
In JavaScript, the same logic is simpler:
acc = [...Array(10).keys()]
.map(x => x + 1)
.filter(x => x % 2 === 0)
.flatMap(x => [x, x * 2])
Can we write analogous code in Python?
Now you can with pysweet:
from pysweet import Iterable_
acc = (
Iterable_(range(10))
.map(lambda x: x + 1)
.filter(lambda x: x % 2 == 0)
.flat_map(lambda x: [x, x * 2])
.to_list()
)
Compared to many excellent alternatives, pysweet is lightweight with fewer than 100 lines of code.
Being only syntactic sugar, pysweet:
has little performance overhead;
does not complicate debugging;
makes onboarding new developers easy.
pysweet has successfully been used in production.
Sweeten Python with pysweet!
Features
Fluent iterable
Iterable with method chaining in the style of JavaScript and Scala.
from pysweet import Iterable_
(
Iterable_([1, 2])
.map(lambda x: x + 1)
.to_list()
)
# [2, 3]
Multi-expression lambda
As in many modern languages, even a systems one like Go.
from pysweet import block_
val = lambda: block_(
x := 1,
x + 1,
)
# val() == 2
Statements as expressions
Composable control flow as in functional languages such as Scala and Haskell.
Bonus: if_ is the ternary operator in the natural order.
from pysweet import if_, try_, raise_
if_(
True,
lambda: 1,
lambda: 2,
)
# 1
try_(
lambda: raise_(Exception('test')),
catch=lambda e: str(e),
)
# 'test'
Documentation
Installation
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
Built Distribution
Hashes for pysweet_func-1.0.8-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5d383a18530953aecf3d31e4a8fcdbef2cfb69a5af9c0e9fb60b8f0b17da41e3 |
|
MD5 | 9b1edf7c2ce5327d9069287e8634be5b |
|
BLAKE2b-256 | 2306cd385e01c1b7fa06e4157736ad85e9504b50cfd05b8df1cdb3b9da398ef9 |