• Stars
    star
    3,248
  • Rank 13,205 (Top 0.3 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 11 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A fancy and practical functional tools

Funcy Build Status =====

A collection of fancy functional tools focused on practicality.

Inspired by clojure, underscore and my own abstractions. Keep reading to get an overview or read the docs. Or jump directly to cheatsheet.

Works with Python 3.4+ and pypy3.

Installation

pip install funcy

Overview

Import stuff from funcy to make things happen:

from funcy import whatever, you, need

Merge collections of same type (works for dicts, sets, lists, tuples, iterators and even strings):

merge(coll1, coll2, coll3, ...)
join(colls)
merge_with(sum, dict1, dict2, ...)

Walk through collection, creating its transform (like map but preserves type):

walk(str.upper, {'a', 'b'})            # {'A', 'B'}
walk(reversed, {'a': 1, 'b': 2})       # {1: 'a', 2: 'b'}
walk_keys(double, {'a': 1, 'b': 2})    # {'aa': 1, 'bb': 2}
walk_values(inc, {'a': 1, 'b': 2})     # {'a': 2, 'b': 3}

Select a part of collection:

select(even, {1,2,3,10,20})                  # {2,10,20}
select(r'^a', ('a','b','ab','ba'))           # ('a','ab')
select_keys(callable, {str: '', None: None}) # {str: ''}
compact({2, None, 1, 0})                     # {1,2}

Manipulate sequences:

take(4, iterate(double, 1)) # [1, 2, 4, 8]
first(drop(3, count(10)))   # 13

lremove(even, [1, 2, 3])    # [1, 3]
lconcat([1, 2], [5, 6])     # [1, 2, 5, 6]
lcat(map(range, range(4)))  # [0, 0, 1, 0, 1, 2]
lmapcat(range, range(4))    # same
flatten(nested_structure)   # flat iter
distinct('abacbdd')         # iter('abcd')

lsplit(odd, range(5))       # ([1, 3], [0, 2, 4])
lsplit_at(2, range(5))      # ([0, 1], [2, 3, 4])
group_by(mod3, range(5))    # {0: [0, 3], 1: [1, 4], 2: [2]}

lpartition(2, range(5))     # [[0, 1], [2, 3]]
chunks(2, range(5))         # iter: [0, 1], [2, 3], [4]
pairwise(range(5))          # iter: [0, 1], [1, 2], ...

And functions:

partial(add, 1)             # inc
curry(add)(1)(2)            # 3
compose(inc, double)(10)    # 21
complement(even)            # odd
all_fn(isa(int), even)      # is_even_int

one_third = rpartial(operator.div, 3.0)
has_suffix = rcurry(str.endswith, 2)

Create decorators easily:

@decorator
def log(call):
    print(call._func.__name__, call._args)
    return call()

Abstract control flow:

walk_values(silent(int), {'a': '1', 'b': 'no'})
# => {'a': 1, 'b': None}

@once
def initialize():
    "..."

with suppress(OSError):
    os.remove('some.file')

@ignore(ErrorRateExceeded)
@limit_error_rate(fails=5, timeout=60)
@retry(tries=2, errors=(HttpError, ServiceDown))
def some_unreliable_action(...):
    "..."

class MyUser(AbstractBaseUser):
    @cached_property
    def public_phones(self):
        return self.phones.filter(public=True)

Ease debugging:

squares = {tap(x, 'x'): tap(x * x, 'x^2') for x in [3, 4]}
# x: 3
# x^2: 9
# ...

@print_exits
def some_func(...):
    "..."

@log_calls(log.info, errors=False)
@log_errors(log.exception)
def some_suspicious_function(...):
    "..."

with print_durations('Creating models'):
    Model.objects.create(...)
    # ...
# 10.2 ms in Creating models

And much more.

Dive in

Funcy is an embodiment of ideas I explain in several essays:

Related Projects

Running tests

To run the tests using your default python:

pip install -r test_requirements.txt
py.test

To fully run tox you need all the supported pythons to be installed. These are 3.4+ and PyPy3. You can run it for particular environment even in absense of all of the above:

tox -e py310
tox -e pypy3
tox -e lint

More Repositories

1

django-cacheops

A slick ORM cache with automatic granular event-driven invalidation.
Python
2,015
star
2

patterns

Pattern matching for python
Python
217
star
3

sublime-reform

A Sublime Text plugin to move through and reform things
Python
179
star
4

whatever

Easy anonymous functions by partial application of operators
Python
99
star
5

handy

Handy django tools
Python
84
star
6

django-pickling

Efficient pickling for django models
Python
73
star
7

pg-bricks

Higher level PostgreSQL client for Node.js
JavaScript
50
star
8

flaws

Finds flaws in your python code
Python
39
star
9

sql-bricks-postgres

Transparent, Schemaless SQL Generation for the PostgreSQL
JavaScript
26
star
10

sublime-hippie-autocomplete

Sublime Text 2/3 style auto completion for ST4
Python
21
star
11

django-easymoney

Easy MoneyField for Django
Python
16
star
12

django-counters

Redis based counters for Django models
Python
15
star
13

CommentsAwareEnter

Smart Enter in line comments in Sublime Text 2/3
Python
15
star
14

djapi

The library of simple helpers to build API with Django.
Python
12
star
15

overload

Overload python 2 functions
Python
10
star
16

aioscrape

Async scraping library
Python
10
star
17

parsechain

Making parsing concise
Python
8
star
18

point-free

Point free async combinators
JavaScript
7
star
19

nesh-history-search

Ctrl-R search for nesh Node.js shell
JavaScript
6
star
20

gzip-reader

Streaming gzip decoder
Python
5
star
21

serverless-docker-artifacts

A Serverless plugin to build your artifacts within docker container
JavaScript
5
star
22

serverless-tesseract

A serverless plugin to add tesseract OCR engine to your artifact
JavaScript
5
star
23

battle-brothers-mods

Mods for Battle Brothers
Squirrel
4
star
24

django-dirty

Track dirty fields on django model
Python
4
star
25

autolink

Convert URL-like and email-like strings into links
Python
4
star
26

postgresql-json

Extract data from PostgreSQL JSON fields.
C
4
star
27

linux-app-logger

An active app/window logger for quantified self purporses
Python
3
star
28

swgoh-tickets-ocr

Recognize SWGOH tickets screenshots
Python
2
star
29

kate-syntax

Modified kate syntax files I used to use
2
star
30

django-union

Unite several querysets into one.
Python
2
star
31

rebind

Rebind hard-coded constants on the fly
Python
2
star
32

sky

A javascript based morph
JavaScript
2
star
33

debug-cache

Cache to speed up debugging
Python
2
star
34

battle-brothers-stdlib

A thing to take the place of lacking/incomplete Squirrel/Battle Brothers standard library
Squirrel
2
star
35

sublime-keylay-replay

A Sublime Text plugin to recover text typed with wrong keyboard layout
Python
1
star
36

aiofilecache

File backend for aiocache
Python
1
star
37

asynx

Async utility extensions
JavaScript
1
star
38

callback-ops

No more "if (err) return callback(err)"
JavaScript
1
star
39

eloquent

Eloquent selection/filter interface
Python
1
star
40

grabber

Web grabber in clojure
Clojure
1
star
41

pytest-matcher

Simplify asserts containing objects and nested data structures
Python
1
star