Funcy

2.0 · active · verified Thu Apr 09

Funcy is a Python library offering a collection of practical functional tools, inspired by Clojure and Underscore.js. It aims to simplify data manipulation and function composition, providing utilities for working with collections, dictionaries, and functions in a functional style. The current stable version is 2.0, released in March 2023, and it supports Python 3.4+ and PyPy3.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates core Funcy operations: `lflatten` for un-nesting collections, `lmap` and `lfilter` for transforming and selecting elements from sequences, `merge` for combining dictionaries, and `first` combined with `drop` and `count` for working with iterators.

from funcy import lmap, lfilter, lflatten, merge, first, drop, count

# Flatten a nested list
data = [1, 2, [3, 4], 5, [6, [7, 8]]]
flattened = lflatten(data)
print(f"Flattened: {flattened}")

# Map and filter a sequence
numbers = [1, 2, 3, 4, 5, 6]
even_squares = lmap(lambda x: x**2, lfilter(lambda x: x % 2 == 0, numbers))
print(f"Even squares: {even_squares}")

# Merge dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = merge(dict1, dict2)
print(f"Merged dict: {merged_dict}")

# Get the Nth item from an infinite sequence using iterators
third_item = first(drop(2, count(1)))
print(f"Third item in count(1): {third_item}")

view raw JSON →