### Install funcy via pip Source: https://github.com/suor/funcy/blob/master/README.rst Install the funcy library using pip. ```bash pip install funcy ``` -------------------------------- ### take(n, seq) examples Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Returns a list of the first n items in the sequence, or all items if fewer than n. The examples show behavior with a list, an infinite count, and a string. ```default take(3, [2, 3, 4, 5]) # [2, 3, 4] take(3, count(5)) # [5, 6, 7] take(3, 'ab') # ['a', 'b'] ``` -------------------------------- ### Install test dependencies and run tests Source: https://github.com/suor/funcy/blob/master/README.rst Install test requirements and run pytest. ```bash pip install -r test_requirements.txt pytest ``` -------------------------------- ### all with isa Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Rewrites the first `all` example using `isa()` for a more concise check that all elements are integers. ```default they_are_ints = all(isa(int), seq) ``` -------------------------------- ### Run type checking tests Source: https://github.com/suor/funcy/blob/master/README.rst Install mypy and pyright, then run type tests. ```bash pip install mypy pyright python type_tests/run.py mypy python type_tests/run.py pyright ``` -------------------------------- ### ilen(seq) example Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Calculates the length of an iterator, consuming it (or hanging if infinite). The example finds the common start length of two strings using takewhile and zip. ```default ilen(takewhile(lambda (x, y): x == y, zip(s1, s2))) ``` -------------------------------- ### zipdict examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Creates a dict from keys and values, stopping at the shorter sequence. ```python zipdict('abcd', range(4)) # -> {'a': 0, 'b': 1, 'c': 2, 'd': 3} zipdict('abc', count()) # -> {'a': 0, 'b': 1, 'c': 2} ``` -------------------------------- ### first(seq) usage examples Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Returns the first item in the sequence, or None if empty. Typical usage is choosing the first of some generated variants, as shown in two examples: getting the first failed validation rule and constructing a form field widget via pattern matching. ```default # Get a text message of first failed validation rule fail = first(rule.text for rule in rules if not rule.test(instance)) # Use simple pattern matching to construct form field widget TYPE_TO_WIDGET = ( [lambda f: f.choices, lambda f: Select(choices=f.choices)], [lambda f: f.type == 'int', lambda f: TextInput(coerce=int)], [lambda f: f.type == 'string', lambda f: TextInput()], [lambda f: f.type == 'text', lambda f: Textarea()], [lambda f: f.type == 'boolean', lambda f: Checkbox(f.label)], ) return first(do(field) for cond, do in TYPE_TO_WIDGET if cond(field)) ``` -------------------------------- ### count(start=0, step=1) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Creates an infinite iterator of values starting at start and incrementing by step. ```APIDOC ## count(start=0, step=1) ### Description Creates an infinite iterator of values: start, start + step, start + 2*step, ... ### Parameters - **start** (number) - Optional - The starting value. Default is 0. - **step** (number) - Optional - The increment between values. Default is 1. ### Returns An infinite iterator of numbers. ``` -------------------------------- ### project example Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Returns a dict with only the specified keys. Useful for shrinking data or constructing a dict of used variables. ```python merge(project(__builtins__, names), project(globals(), names)) ``` -------------------------------- ### nth(n, seq) example Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Returns the nth item (0-indexed) or None if it doesn't exist. The example gets the 6th line of a file using repeatedly. ```default nth(5, repeatedly(open('some_file').readline)) ``` -------------------------------- ### set_in examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Creates a nested collection with a value set at the path, without modifying the original. ```python set_in({"a": {"b": 42}}, ["a", "b"], 10) # -> {"a": {"b": 10}} set_in({"a": {"b": 42}}, ["a", "c"], 10) # -> {"a": {"b": 42, "c": 10}} ``` -------------------------------- ### partition to structure user credentials Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Iterates over partitions of `n` items. The example structures user credentials into a dict using `partition(3, ...)`. ```python # Structure user credentials {id: (name, password) for id, name, password in partition(3, users)} ``` -------------------------------- ### select_values() examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Selects part of a dict or collection of pairs with values passing the predicate. Examples leave only str values and construct a dict of methods. ```default # Leave only str values select_values(isa(str), values) # Construct a dict of methods select_values(inspect.isfunction, cls.__dict__) ``` -------------------------------- ### Example PR description for memoize() fix Source: https://github.com/suor/funcy/blob/master/CONTRIBUTING.md Shows the recommended structure for a PR description: what is broken, the fix, how it was found, benchmark results, and notes on tests and docs. Includes a benchmark table comparing cache key variants and a list of tried alternatives with their trade-offs. ```markdown memoize() mixes up positional and keyword args: `f(('x', 1))` and `f(x=1)` share a cache entry. Fixed with `(MARK, args, frozenset(kwargs.items()))` as a cache key. `frozenset` is faster than `tuple(sorted(...))`, which is used now. Found by code reading, no real case. - benchmarked 9 variants, including MARK in the middle. The selected one is on par with or better than master. - tests: added the fail from title and a couple more tricky ones. - no docs changes. --- Cache hits, vs master: | key | f(1) | f(1, y=2) | f(x=1, y=2) | f(1, y=2, z=3, w=4) | |---------------------------------------------|-------|-----------|-------------|---------------------| | master: `args + tuple(sorted(...))` | 65 ns | 246 ns | 273 ns | 386 ns | | `args + MARK + tuple(sorted(...))` | ±0% | +9% | +10% | +5% | | `(*args, MARK, *sorted(...))` | ±0% | +11% | +13% | +7% | | `args + MARK + (frozenset(...),)` | ±0% | +13% | +10% | -6% | | `(MARK, args, frozenset(...))`, selected | ±0% | -1% | -1% | -13% | | `(args, tuple(sorted(...)))` | ±0% | +5% | +9% | +3% | | `args + (frozenset(...),)` | ±0% | +2% | -2% | -13% | | `(args, frozenset(...))` | ±0% | -4% | -3% | -16% | | `args + MARK + tuple(kwargs.items())` | ±0% | -11% | -14% | -24% | Tried: - variants without MARK: collide with positional args, e.g. `(args, frozenset(...))` with `f((), frozenset(...))` - `args + MARK + tuple(kwargs.items())`: fastest, but `f(a=1, b=2)` and `f(b=2, a=1)` get separate entries, so `invalidate()` misses Same key in `invalidate()`, covers both `memoize()` and `cache()`. `.memory` keys change for kwargs calls; memory is in-process only, so nothing breaks. ... ``` -------------------------------- ### iterate: recursive sequence examples Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows iterate generating sequences: incrementing from 5, doubling from 1, and Fibonacci via a step function. ```default iterate(inc, 5) # -> 5, 6, 7, 8, 9, ... iterate(lambda x: x * 2, 1) # -> 1, 2, 4, 8, 16, ... step = lambda p: (p[1], p[0] + p[1]) map(first, iterate(step, (0, 1))) # -> 0, 1, 1, 2, 3, 5, 8, ... (Fibonacci sequence) ``` -------------------------------- ### Quick Start Commands for .pyih Stub Generation Source: https://github.com/suor/funcy/blob/master/PYIH.md Commands to edit a .pyih source file, regenerate all .pyi files, and run type checkers (mypy, pyright, ty, pyrefly). ```bash # Edit the .pyih source vim funcy/seqs.pyih # Regenerate all .pyi files python translate_pyih.py # Verify types python type_tests/run.py mypy python type_tests/run.py pyright python type_tests/run.py ty python type_tests/run.py pyrefly ``` -------------------------------- ### count(start=0, step=1) Source: https://github.com/suor/funcy/blob/master/docs/cheatsheet.rst Creates an infinite iterator of values starting at start and incrementing by step. ```APIDOC ## count(start=0, step=1) ### Description Creates an infinite iterator of values: start, start + step, start + 2*step, ... ### Parameters - **start** (number) - Optional - Starting value (default 0) - **step** (number) - Optional - Increment step (default 1) ### Returns An infinite iterator of numbers. ``` -------------------------------- ### Passthrough Example Source: https://github.com/suor/funcy/blob/master/PYIH.md Functions without XFunc, XPred, or collection type parameters pass through verbatim. ```python def take(n: int, seq: Iterable[_T]) -> list[_T]: ... # copied as-is ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Get the object wrapped by func. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by func. ### Parameters - **func** (callable) - Required - The function to unwrap. ### Returns The object wrapped by func. ``` -------------------------------- ### flip example Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Flips keys and values of a mapping, preserving collection type. ```python flip(OrderedDict(['aA', 'bB'])) # -> OrderedDict([('A', 'a'), ('B', 'b')]) ``` -------------------------------- ### re_find examples Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Shows how re_find returns matches in simplest form based on captures. No captures returns matched string, single positional capture returns substring, only positional captures return tuple, only named captures return dict, mixed returns match object. Returns None on mismatch. ```default # Find first number in a line silent(int)(re_find(r'\d+', line)) # Find number of men in a line re_find(r'(\d+) m[ae]n', line) # Parse uri into nice dict re_find(r'^/post/(?P\d+)/(?P\w+)$', uri) ``` -------------------------------- ### get_lax examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst A version of get_in that tolerates type mismatches along the path, returning the default instead of raising TypeError. ```python get_lax([1, 2, 3], ["a"], "foo") # -> "foo" get_lax({"a": None}, ["a", "b"]) # -> None ``` -------------------------------- ### has_path examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Checks if a path exists in a nested collection. ```python has_path({"a": {"b": 42}}, ["a", "b"]) # -> True has_path({"a": {"b": 42}}, ["c"]) # -> False has_path({"a": [1, 2]}, ["a", 0]) # -> True ``` -------------------------------- ### walk() on strings Source: https://github.com/suor/funcy/blob/master/docs/colls.rst walk() works with strings, mapping each character. Examples show doubling characters and converting to ord. ```default walk(lambda x: x * 2, 'ABC') # -> 'AABBCC' walk(compose(str, ord), 'ABC') # -> '656667' ``` -------------------------------- ### Build documentation Source: https://github.com/suor/funcy/blob/master/CLAUDE.md Builds HTML documentation with warnings treated as errors. ```bash cd docs && sphinx-build -b html -W . _build/html ``` -------------------------------- ### Collection Type Expansion Example Source: https://github.com/suor/funcy/blob/master/PYIH.md Uses PEP 695 type parameter syntax to generate one overload per concrete type (list, set, frozenset), substituting C throughout. Combines with XFunc/XPred for quadratic expansion, generating 3 * 7 = 21 overloads. ```python def walk[C: (list, set, frozenset)](f: XFunc[[A], B], coll: C[A]) -> C[B]: ... ``` -------------------------------- ### update_in example Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Creates a nested collection with a value at the path updated using the given function. ```python update_in({"a": {}}, ["a", "cnt"], inc, default=0) # -> {"a": {"cnt": 1}} ``` -------------------------------- ### zip_values example Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Yields tuples of corresponding values from multiple dicts, skipping keys not present in all. ```python error = sum((x - y) ** 2 for x, y in zip_values(result, reference)) ``` -------------------------------- ### @LazyObject delayed initialization Source: https://github.com/suor/funcy/blob/master/docs/objects.rst Creates an object that initializes only on first attribute access, delaying setup until first use. The example shows a redis client that is created only when first accessed. ```default @LazyObject def redis_client(): if isinstance(settings.REDIS, str): return StrictRedis.from_url(settings.REDIS) else: return StrictRedis(**settings.REDIS) # Will be only created on first use redis_client.set(...) ``` -------------------------------- ### lsplit with re_tester to separate private and public attributes Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Splits sequence items into two lists based on a predicate. The example separates private attributes (starting with underscore) from public ones using `re_tester('^_')`. ```python private, public = lsplit(re_tester('^_'), dir(instance)) ``` -------------------------------- ### walk() on dict with swap lambda Source: https://github.com/suor/funcy/blob/master/docs/colls.rst When walking a dict, (key, value) pairs are mapped. This example flips keys and values. ```default swap = lambda (k, v): (v, k) walk(swap, {1: 10, 2: 20}) ``` -------------------------------- ### zip_dicts examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Yields key, (value1, value2, ...) tuples for common keys of all dicts. Useful for processing multiple dicts at once. ```python changed_items = [id for id, (new, old) in zip_dicts(items, old_items) if abs(new - old) >= PRECISION] lines = {id: cnt * price for id, (cnt, price) in zip_dicts(amounts, prices)} ``` -------------------------------- ### lsplit_by with bool to split sequence at first falsy item Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Splits the start of a sequence that passes the predicate from the rest. The example shows `lsplit_by(bool, iter([-2, -1, 0, 1, 2]))` returning `[-2, -1]` and `[0, 1, 2]`. ```python lsplit_by(bool, iter([-2, -1, 0, 1, 2])) # [-2, -1], [0, 1, 2] ``` -------------------------------- ### count_(start=0, step=1) Source: https://github.com/suor/funcy/blob/master/docs/descriptions.html Makes an infinite iterator of values: start, start + step, start + 2*step, ... ```APIDOC ## count_(start=0, step=1) ### Description Makes an infinite iterator of values: `start, start + step, start + 2*step, ...` ### Parameters - **start** (number) - Optional - Starting value (default 0) - **step** (number) - Optional - Step increment (default 1) ### Returns Iterator of values starting at `start` and incrementing by `step` indefinitely. ``` -------------------------------- ### count(start=0, step=1) Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Makes an infinite iterator of values: start, start + step, start + 2*step, ... ```APIDOC ## count(start=0, step=1) ### Description Makes an infinite iterator of values: start, start + step, start + 2*step, ... ### Parameters - **start** (number) - Optional - The starting value. Default is 0. - **step** (number) - Optional - The increment between values. Default is 1. ### Returns An infinite iterator of values. ``` -------------------------------- ### get_in examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Returns a value at a path in a nested collection. Missing keys or indices return the default, but type mismatches raise TypeError. ```python get_in({"a": {"b": 42}}, ["a", "b"]) # -> 42 get_in({"a": {"b": 42}}, ["c"], "foo") # -> "foo" ``` -------------------------------- ### count(start=0, step=1) Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Makes an infinite iterator of values: `start, start + step, start + 2*step, ...`. Useful for generating sequences or annotating with `zip()`. ```APIDOC ## count(start=0, step=1) ### Description Makes an infinite iterator of values: `start, start + step, start + 2*step, ...`. Useful for generating sequences or annotating with `zip()`. ### Parameters - **start** (optional, default=0) - The starting value. - **step** (optional, default=1) - The increment between values. ### Returns An infinite iterator of values. ### Example ```default map(lambda x: x ** 2, count(1)) # -> 1, 4, 9, 16, ... zip(count(), 'abcd') # -> (0, 'a'), (1, 'b'), (2, 'c'), (3, 'd') ``` ``` -------------------------------- ### select() examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Filters elements of a collection by predicate, constructing a collection of same type. For dicts, pred receives (key, value) pairs. ```default select(even, {1, 2, 3, 10, 20}) # -> {2, 10, 20} select(lambda (k, v): k == v, {1: 1, 2: 3}) # -> {1: 1} select(lambda x: x > 32, b'as hey\tthere') # -> b'asheythere' ``` -------------------------------- ### count(start=0, step=1) Source: https://github.com/suor/funcy/blob/master/docs/calc.rst Makes an infinite iterator of values: start, start + step, start + 2*step, ... ```APIDOC ## count(start=0, step=1) ### Description Makes an infinite iterator of values: start, start + step, start + 2*step, ... ### Parameters - **start** (number) - Optional - The starting value. Default is 0. - **step** (number) - Optional - The increment between values. Default is 1. ### Returns An infinite iterator of numbers. ``` -------------------------------- ### @wrap_with(ctx) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Turn context manager into a decorator. ```APIDOC ## @wrap_with(ctx) ### Description Turn context manager into a decorator. ### Parameters - **ctx** (context manager) - Required - The context manager to use as a decorator. ### Usage Use as a decorator on a function to wrap its execution in the given context manager. ``` -------------------------------- ### Run a single test file Source: https://github.com/suor/funcy/blob/master/CLAUDE.md Executes all tests in the specified test file. ```bash pytest tests/test_seqs.py ``` -------------------------------- ### nullcontext(enter_result=None) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst A noop context manager. ```APIDOC ## nullcontext(enter_result=None) ### Description A noop context manager. ### Parameters - **enter_result** (any) - Optional - The value to return from __enter__. ### Returns - **context manager** - A context manager that does nothing. ``` -------------------------------- ### LazyObject(init) Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Creates an object that sets itself up on first use. The initialization is deferred until an attribute is accessed. ```APIDOC ## LazyObject(init) ### Description Creates an object that sets itself up on first use. The initialization is deferred until an attribute is accessed. ### Parameters - **init** (callable) - Required - A callable that returns the actual object to be used. ### Returns A lazy object that initializes on first attribute access. ``` -------------------------------- ### count(start=0, step=1) Source: https://github.com/suor/funcy/blob/master/docs/objects.rst Creates an infinite iterator of values starting from start and incrementing by step. ```APIDOC ## count(start=0, step=1) ### Description Creates an infinite iterator of values: start, start + step, start + 2*step, ... ### Parameters - **start** (int) - Optional - Starting value (default 0) - **step** (int) - Optional - Increment step (default 1) ### Returns An infinite iterator of numbers. ``` -------------------------------- ### curry: make partial factory Source: https://github.com/suor/funcy/blob/master/docs/funcs.rst Handy to make a partial factory. ```default make_tester = curry(re_test) is_word = make_tester(r'^\w+$') is_int = make_tester(r'^[1-9]\d*$') ``` -------------------------------- ### chunks with step to split string into chunks of size 2 and step 4 Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Like `partition` but may include a final chunk with fewer than `n` items. The example splits 'abcde' into 'ab' and 'e' using step 4. ```python chunks(2, 4, 'abcde') # -> 'ab', 'e' ``` -------------------------------- ### drop(n, seq) examples Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Skips first n items in the sequence, returning an iterator yielding the rest. The examples show behavior with a list, an infinite count, and a string. ```default drop(3, [2, 3, 4, 5]) # iter([5]) drop(3, count(5)) # count(8) drop(3, 'ab') # empty iterator ``` -------------------------------- ### where: iterator version for first match Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Iterator version of where for efficiency when only the first match is needed. Example finds the first play by Shakespeare. ```default first(where(plays, author="Shakespeare")) # => {"title": "The Two Gentlemen of Verona", ...} ``` -------------------------------- ### nullcontext(enter_result=None) Source: https://github.com/suor/funcy/blob/master/docs/colls.rst A noop context manager. ```APIDOC ## nullcontext(enter_result=None) ### Description A noop context manager. ### Parameters - **enter_result** (any) - Optional - The value to return from __enter__. ### Returns A context manager that does nothing. ``` -------------------------------- ### partition to make a dict from flat list of pairs Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Iterates over partitions of `n` items. The example creates a dict from a flat list of pairs using `partition(2, ...)`. ```python # Make a dict from flat list of pairs dict(partition(2, flat_list_of_pairs)) ``` -------------------------------- ### XFunc Extended Mapper Example Source: https://github.com/suor/funcy/blob/master/PYIH.md Defines a function parameter using the extended function protocol (Callable, None, Set, Regex, int, slice, Mapping) that transforms values from type A to type B. Expands to 7 overloads. ```python def map(f: XFunc[[A], B], seq: Iterable[A]) -> Iterator[B]: ... ``` -------------------------------- ### count(start=0, step=1) Source: https://github.com/suor/funcy/blob/master/docs/extended_fns.rst Creates an infinite iterator of values starting at start and incrementing by step each time. Useful for generating sequences without explicit loops. ```APIDOC ## count(start=0, step=1) ### Description Creates an infinite iterator of values: start, start + step, start + 2*step, ... ### Parameters - **start** (number) - Optional - The first value in the sequence. Default is 0. - **step** (number) - Optional - The increment between values. Default is 1. ### Returns An infinite iterator of numbers. ``` -------------------------------- ### Run tox environments Source: https://github.com/suor/funcy/blob/master/CLAUDE.md Runs various tox environments for multi-version testing, linting, docs, type tests, and stub tests. ```bash tox -e py313 ``` ```bash tox -e lint ``` ```bash tox -e docs ``` ```bash tox -e typetest ``` ```bash tox -e stubtest ``` -------------------------------- ### throttle(60) decorator example Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Limits the decorated function to run at most once per given period (in seconds). The example shows a process_beat function that updates progress no more often than once a minute. ```python @throttle(60) def process_beat(pk, progress): Model.objects.filter(pk=pk).update(beat=timezone.now(), progress=progress) # Processing something, update progress info no more often then once a minute for i in ...: process_beat(pk, i / n) # ... do actual processing ``` -------------------------------- ### Run all tests with pytest Source: https://github.com/suor/funcy/blob/master/CLAUDE.md Runs the full test suite with warnings treated as errors. ```bash pytest -W error ``` -------------------------------- ### chunks to split string into chunks of size 2 Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Like `partition` but may include a final chunk with fewer than `n` items. The example splits 'abcde' into 'ab', 'cd', 'e'. ```python chunks(2, 'abcde') # -> 'ab', 'cd', 'e' ``` -------------------------------- ### class LazyObject(init) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Creates an object that sets itself up on first use. Useful for lazy initialization. ```APIDOC ## class LazyObject(init) ### Description Creates an object that sets itself up on first use. Useful for lazy initialization. ### Parameters - **init** (callable) - Required - A callable that initializes the object. ### Returns - **LazyObject** - An instance of LazyObject. ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Get the object wrapped by func. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by func. ### Parameters - **func** (callable) - Required - The function to unwrap. ### Returns The original object that was wrapped. ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/decorators.rst Get the object wrapped by the given function. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by the given function. ### Parameters - **func** (callable) - Required - The function to unwrap. ### Returns The original object that was wrapped by the function. ``` -------------------------------- ### Lint with flake8 Source: https://github.com/suor/funcy/blob/master/CLAUDE.md Lints the main package and tests with selected rules. ```bash flake8 funcy ``` ```bash flake8 --select=F,E5,W tests ``` -------------------------------- ### walk_keys() examples Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Walks keys of a mapping or collection of pairs, mapping them with the given function. Preserves collection type for dict, defaultdict, OrderedDict, or other mapping classes. ```default walk_keys(str.upper, {'a': 1, 'b': 2}) # {'A': 1, 'B': 2} walk_keys(int, json.loads(some_dict)) # restore key type lost in translation ``` -------------------------------- ### Run tox environments Source: https://github.com/suor/funcy/blob/master/README.rst Run tox for specific environments. ```bash tox -e py310 tox -e pypy3 tox -e lint tox -e typetest tox -e stubtest ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/objects.rst Get the object wrapped by func. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by func. ### Parameters - **func** (callable) - Required - The function to unwrap. ``` -------------------------------- ### @once Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Let function execute only once. Noop all subsequent calls. ```APIDOC ## @once ### Description Let function execute only once. Noop all subsequent calls. ### Usage Use as a decorator on a function to ensure it runs only once. ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/cheatsheet.rst Get the object wrapped by func. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by func. ### Parameters - **func** (callable) - Required - The wrapped function. ``` -------------------------------- ### fallback(*approaches) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Tries several approaches until one works. Each approach has a form of (callable, errors). ```APIDOC ## fallback(*approaches) ### Description Tries several approaches until one works. Each approach has a form of (callable, errors). ### Parameters - **approaches** (tuple) - Required - Each approach is a tuple of (callable, errors) where errors is an exception type or tuple of exception types to catch. ### Returns - **any** - The result of the first approach that succeeds. ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Get the object wrapped by the given function. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by the given function. ### Parameters - **func** (callable) - Required - The function to unwrap. ### Returns The original wrapped object. ``` -------------------------------- ### project(mapping, keys) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Leaves only given keys in mapping. ```APIDOC ## project(mapping, keys) ### Description Leaves only given keys in mapping. ### Parameters - **mapping** (dict) - Required - The dictionary to project. - **keys** (iterable) - Required - The keys to keep. ### Returns - **dict** - The projected dictionary. ``` -------------------------------- ### partial(func, *args, **kwargs) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Returns partial application of func. ```APIDOC ## partial(func, *args, **kwargs) ### Description Returns partial application of func. ### Parameters - **func** (callable) - Required - The function to partially apply. - **args** - Required - Positional arguments to bind. - **kwargs** - Required - Keyword arguments to bind. ### Returns - **callable** - A partial application of func. ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/extended_fns.rst Get the object wrapped by the given function. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by the given function. ### Parameters - **func** (callable) - Required - The function to unwrap. ### Returns The wrapped object. ``` -------------------------------- ### re_iter example Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Parses an ini section into a dict using re_iter with a regex that captures key-value pairs. re_iter returns a list or iterator of all matches in simplest form. ```default # A fast and dirty way to parse ini section into dict dict(re_iter('(\w+)=(\w+)', ini_text)) ``` -------------------------------- ### take(n, seq) Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Returns a list of the first n items in the sequence, or all items if there are fewer than n. ```APIDOC ## take(n, seq) ### Description Returns a list of the first `n` items in the sequence, or all items if there are fewer than `n`. ### Parameters - **n** (int) - Required - The number of items to take. - **seq** (sequence) - Required - The sequence to take items from. ### Returns - A list of the first `n` items, or all items if fewer than `n`. ``` -------------------------------- ### ltree_nodes(root, follow=is_seqcont, children=iter) Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Lists all the tree nodes. For example, you can list all classes in a hierarchy. ```APIDOC ## ltree_nodes(root, follow=is_seqcont, children=iter) ### Description A way to list all the tree nodes. For example, you can list all classes in a hierarchy. ### Method Function call ### Parameters - **root** (object) - Required - The root of the tree. - **follow** (callable) - Optional - A predicate that determines whether to descend into a node. Defaults to `is_seqcont`. - **children** (callable) - Optional - A function that returns the children of a node. Defaults to `iter`. ### Returns A list of the nodes of the tree. ### Example ```python ltree_nodes(Base, children=type.__subclasses__, follow=type.__subclasses__) ``` ``` -------------------------------- ### ltree_leaves(root, follow=is_seqcont, children=iter) Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Lists all the tree leaves. For example, you can list all descendants of a class. ```APIDOC ## ltree_leaves(root, follow=is_seqcont, children=iter) ### Description A way to list all the tree leaves. For example, you can list all descendants of a class. ### Method Function call ### Parameters - **root** (object) - Required - The root of the tree. - **follow** (callable) - Optional - A predicate that determines whether to descend into a node. Defaults to `is_seqcont`. - **children** (callable) - Optional - A function that returns the children of a node. Defaults to `iter`. ### Returns A list of the leaves of the tree. ### Example ```python ltree_leaves(Base, children=type.__subclasses__, follow=type.__subclasses__) ``` ``` -------------------------------- ### partial(func, *args, **kwargs) Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Returns partial application of the given function. ```APIDOC ## partial(func, *args, **kwargs) ### Description Returns partial application of `func`. ### Parameters - **func** - The function to partially apply. - **args** - Positional arguments to bind. - **kwargs** - Keyword arguments to bind. ### Returns A partial application of the function. ``` -------------------------------- ### re_all(regex, s, flags=0) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Lists all matches of the given regex in the string s. ```APIDOC ## re_all(regex, s, flags=0) ### Description Lists all matches of regex in s. ### Parameters - **regex** (string) - Required - The regular expression pattern. - **s** (string) - Required - The string to search. - **flags** (integer) - Optional - Regex flags. Default is 0. ### Returns A list of all matches. ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/types.rst Get the object wrapped by the given function. Returns the underlying function or object. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by func. ### Parameters - **func** (callable) - Required - The function to unwrap. ### Returns - **object** - The wrapped object. ``` -------------------------------- ### tap(x, label=None) Source: https://github.com/suor/funcy/blob/master/docs/cheatsheet.rst Prints x and then returns it. ```APIDOC ## tap(x, label=None) ### Description Prints x and then returns it. ### Parameters - **x** (any) - Required - Value to print and return. - **label** (str) - Optional - Label to prefix the print. ``` -------------------------------- ### unwrap(func) Source: https://github.com/suor/funcy/blob/master/docs/calc.rst Get the object wrapped by func. ```APIDOC ## unwrap(func) ### Description Get the object wrapped by func. ### Parameters - **func** (callable) - Required - The wrapped function. ### Returns The wrapped object. ``` -------------------------------- ### func_partial(func, *args, **kwargs) Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Like partial() but returns a real function. ```APIDOC ## func_partial(func, *args, **kwargs) ### Description Like `partial()` but returns a real function. ### Parameters - **func** - The function to partially apply. - **args** - Positional arguments to bind. - **kwargs** - Keyword arguments to bind. ### Returns A real function with the given arguments partially applied. ``` -------------------------------- ### rest(seq) Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Skips the first item in the sequence, returning an iterator starting just after it. A shortcut for drop(1, seq). ```APIDOC ## rest(seq) ### Description Skips the first item in the sequence, returning an iterator starting just after it. A shortcut for `drop(1, seq)`. ### Parameters - **seq** (iterable) - Required - The sequence to get the rest from. ### Returns - **iterator** - Iterator over the items after the first. ``` -------------------------------- ### autocurry(func) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Creates a version of func returning its partial applications until sufficient arguments are passed. ```APIDOC ## autocurry(func) ### Description Creates a version of func returning its partial applications until sufficient arguments are passed. ### Parameters - **func** (callable) - Required - The function to curry. ### Returns - **callable** - A curried version of func. ``` -------------------------------- ### log_durations() decorator Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Time each function call and log its duration. The example shows the output format. ```python @log_durations(logging.info) def do_hard_work(n): samples = range(n) # ... # 121 ms in do_hard_work(10) # 143 ms in do_hard_work(11) # ... ``` -------------------------------- ### @joining(sep) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Joins decorated function results with sep. ```APIDOC ## @joining(sep) ### Description Joins decorated function results with sep. ### Parameters - **sep** (str) - Required - The separator to join results with. ### Usage Use as a decorator on a function that returns an iterable to join its elements into a string. ``` -------------------------------- ### @decorator Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Transforms a flat wrapper into a decorator. ```APIDOC ## @decorator ### Description Transforms a flat wrapper into a decorator. ### Usage Use as a decorator on a function that takes a function and returns a wrapped function. ``` -------------------------------- ### LazyObject(init) Source: https://github.com/suor/funcy/blob/master/docs/funcs.rst Creates an object that sets itself up on first use. ```APIDOC ## class LazyObject(init) ### Description Creates an object setting itself up on first use. ### Parameters - **init** - A callable that initializes the object. ### Usage Instantiate with an initializer function. ``` -------------------------------- ### class LazyObject(init) Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Creates an object that sets itself up on first use. The initialization is deferred until the first attribute access. ```APIDOC ## class LazyObject(init) ### Description Creates an object that sets itself up on first use. The initialization is deferred until the first attribute access. ### Parameters - **init** (callable) - Required - A callable that initializes the object. ### Returns A lazy object. ``` -------------------------------- ### print_iter_durations() in a loop Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Wrap an iterable to log the duration of processing each item. The example shows the output format. ```python for item in print_iter_durations(seq, label='hard work'): do_smth(item) # 121 ms in iteration 0 of hard work # 143 ms in iteration 1 of hard work # ... ``` -------------------------------- ### mapcat() to flatten lines and extract numbers Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Uses mapcat() to get all lines from multiple texts and to extract all numbers from strings. ```default # Get all the lines of all the texts in single flat list mapcat(str.splitlines, bunch_of_texts) # Extract all numbers from strings mapcat(partial(re_all, r'\d+'), bunch_of_strings) ``` -------------------------------- ### class LazyObject(init) Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Creates an object that sets itself up on first use. ```APIDOC ## class LazyObject(init) ### Description Creates an object setting itself up on first use. ### Parameters - **init** - The initialization function or value. ### Usage Instantiate with an init function or value. ``` -------------------------------- ### with_prev(seq, fill=None) Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Yields each item from the sequence along with the one preceding it. ```APIDOC ## with_prev(seq, fill=None) ### Description Yields each item from the sequence along with the one preceding it. ### Parameters - **seq** (sequence) - Required - The input sequence. - **fill** (optional) - Default None - Value to use for the first item's predecessor. ### Returns An iterator of tuples, each containing an item and its predecessor. ``` -------------------------------- ### split_by(pred, seq) / lsplit_by(pred, seq) Source: https://github.com/suor/funcy/blob/master/docs/types.rst Splits the start of the sequence, consisting of items passing pred, from the rest of it. ```APIDOC ## split_by(pred, seq) / lsplit_by(pred, seq) ### Description Splits the start of the sequence, consisting of items passing `pred`, from the rest of it. ### Parameters - **pred** (callable) - Required - The predicate to test items. - **seq** (sequence) - Required - The input sequence. ### Returns - A tuple `(start, tail)` where `start` contains items passing `pred` and `tail` is the rest. ``` -------------------------------- ### split_by(pred, seq) / lsplit_by(pred, seq) Source: https://github.com/suor/funcy/blob/master/docs/funcs.rst Splits the start of the sequence, consisting of items passing pred, from the rest of it. ```APIDOC ## split_by(pred, seq) / lsplit_by(pred, seq) ### Description Splits the start of the sequence, consisting of items passing pred, from the rest of it. ### Parameters - **pred** - A predicate function to test items. - **seq** - The sequence to split. ### Returns A tuple (start, rest) where start contains items passing pred and rest contains the remaining items. ``` -------------------------------- ### partial(func, *args, **kwargs) Source: https://github.com/suor/funcy/blob/master/docs/decorators.rst Returns partial application of func. ```APIDOC ## partial(func, *args, **kwargs) ### Description Returns partial application of `func`. ### Parameters - **func** (callable) - Required - Function to partially apply. - **args** - Optional - Positional arguments to bind. - **kwargs** - Optional - Keyword arguments to bind. ### Returns A partial application of `func` with the given arguments. ``` -------------------------------- ### keep() and lkeep() equivalence shortcuts Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows the equivalence of keep() and lkeep() with filter() and map(). These are handy shortcuts for filtering falsy elements. ```default keep(f, seq) == filter(bool, map(f, seq)) keep(seq) == filter(bool, seq) lkeep(f, seq) == lfilter(bool, map(f, seq)) lkeep(seq) == lfilter(bool, seq) ``` -------------------------------- ### del_in example Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Creates a nested collection with the path removed. Returns the collection as-is if the path is missing. ```python del_in({"a": [1, 2, 3]}, ["a", 1]) # -> {"a": [1, 3]} ``` -------------------------------- ### LazyObject(init) Source: https://github.com/suor/funcy/blob/master/docs/decorators.rst Creates an object that sets itself up on first use. Useful for lazy initialization. ```APIDOC ## LazyObject(init) ### Description Creates an object setting itself up on first use. ### Parameters - **init** (callable) - Required - A callable that initializes the object when first accessed. ### Returns A lazy object that initializes on first attribute access. ``` -------------------------------- ### all_fn(*fs) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Constructs a predicate, which holds when all fs hold. ```APIDOC ## all_fn(*fs) ### Description Constructs a predicate, which holds when all fs hold. ### Parameters - **fs** (callable) - Required - The predicates to combine. ### Returns - **callable** - A predicate that returns True if all fs return True. ``` -------------------------------- ### print_durations() context manager Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Time a block of code using a context manager. The example shows the output format. ```python with print_durations('Creating models'): Model.objects.create(...) # ... # 10.2 ms in Creating models ``` -------------------------------- ### sums(seq[, acc]) / lsums(seq[, acc]) Source: https://github.com/suor/funcy/blob/master/docs/decorators.rst Returns a sequence of partial sums of seq. Optionally starts with an initial accumulator. ```APIDOC ## sums(seq[, acc]) / lsums(seq[, acc]) ### Description Returns a sequence of partial sums of seq. ### Parameters - **seq** (iterable) - Required - Sequence of numbers. - **acc** (optional) - Initial accumulator value. ### Returns Sequence of partial sums. ``` -------------------------------- ### reductions: intermediate reduction values Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Yields intermediate values of reducing seq by f, as shown in the example. Use sums() for partial sums. ```default reduce(f, seq[:1], [acc]), reduce(f, seq[:2], [acc]), ... ``` -------------------------------- ### group_by_keys to group sentences by words Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Groups elements that have multiple keys into a `defaultdict(list)`. The example groups sentences by their words using `str.split`. ```python sentences_with_word = group_by_keys(str.split, sentences) ``` -------------------------------- ### identity(x) Source: https://github.com/suor/funcy/blob/master/docs/decorators.rst Returns its argument. ```APIDOC ## identity(x) ### Description Returns its argument. ### Parameters - **x** (any) - Required - Value to return. ### Returns The argument `x`. ``` -------------------------------- ### Verify stubs match runtime signatures Source: https://github.com/suor/funcy/blob/master/CLAUDE.md Runs stubtest via tox to ensure type stubs align with runtime signatures. ```bash tox -e stubtest ```