Composable Python via syntactic sugar
Project description
Why pysweet?
Python can sometimes be unwieldy.
Consider the following 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 imperative style can grow complex as requirements evolve;
The comprehension style can get complicated when nested;
The functional style is not very readable in Python.
In JavaScript, the same logic can be written:
acc = [...Array(10).keys()]
.map(x => x + 1)
.filter(x => x % 2 === 0)
.flatMap(x => [x, x * 2])
With pysweet, we can analogously write:
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()
)
pysweet offers many other similar features.
pysweet is:
lightweight, with ~100 lines of code;
mostly syntactic sugar, hence performant, easy to debug, and easy to learn;
in production use.
Sweeten Python with pysweet!
Select features
Iterable with method chaining, cf. JavaScript and Scala:
from pysweet import Iterable_
(
Iterable_([1, 2])
.map(lambda x: x + 1)
.to_list()
)
# [2, 3]
Multi-expression lambda, common in modern languages:
from pysweet import block_
val = lambda: block_(
x := 1,
x + 1,
)
# val() == 2
Statement as expression, cf. Scala and Haskell:
(if_ is also the ternary operator)
from pysweet import if_, try_, raise_
if_(
True,
lambda: 1,
lambda: 2,
)
# 1
try_(
lambda: raise_(Exception('test')),
catch=lambda e: str(e),
)
# 'test'
Resources
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.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 63cd950cc4bd7c194bfc0fd24a8c83cb72d21d5be35f940445234e06fde00a04 |
|
MD5 | 599af937a861efc9abe6da351cef563f |
|
BLAKE2b-256 | 7904517d9020973909b9e26ad5acc0830d614824142d23fe68647f0ef54d6d53 |