### Install Funcy Python Library Source: https://github.com/suor/funcy/blob/master/README.rst Installs the Funcy library using pip, the standard package installer for Python. This command fetches the latest version from PyPI and makes it available in your Python environment. ```Shell pip install funcy ``` -------------------------------- ### Numbering Lines with Count and Zip in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Provides an example of using `funcy.count` starting from 10 with a step of 10, combined with `zip` and `splitlines`, to print lines of code with BASIC-style numbered prefixes. ```python for line in zip(count(10, 10), code.splitlines()): print '%d %s' % line ``` -------------------------------- ### Install funcy with pip (Shell) Source: https://github.com/suor/funcy/blob/master/docs/overview.rst This command uses the pip package installer for Python to download and install the funcy library from the Python Package Index (PyPI). This is the standard way to add funcy to your Python environment. ```Shell pip install funcy ``` -------------------------------- ### Install Test Requirements for Funcy Source: https://github.com/suor/funcy/blob/master/README.rst Installs the necessary Python packages required to run the Funcy test suite. This command reads dependencies from a `test_requirements.txt` file. ```Shell pip install -r test_requirements.txt ``` -------------------------------- ### Generating Sequence with Count and Map in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `funcy.count` to generate an infinite sequence of numbers starting from 1 and apply a transformation (squaring) using `map`. ```python map(lambda x: x ** 2, count(1)) # -> 1, 4, 9, 16, ... ``` -------------------------------- ### Calculating Common Prefix Length Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use the `ilen` function in conjunction with `takewhile` and `zip` to efficiently calculate the length of the common starting sequence between two strings, `s1` and `s2`. ```Python ilen(takewhile(lambda (x, y): x == y, zip(s1, s2))) ``` -------------------------------- ### Generating Geometric Sequence with Iterate in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `funcy.iterate` with a function that doubles its input and a starting value (1) to generate an infinite geometric sequence. ```python iterate(lambda x: x * 2, 1) # -> 1, 2, 4, 8, 16, ... ``` -------------------------------- ### Selecting Dictionary Keys with project in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Shows how `funcy.project` creates a new dictionary containing only specified keys from an existing mapping. The example combines it with `merge` to collect variables from different scopes. ```python merge(project(__builtins__, names), project(globals(), names)) ``` -------------------------------- ### Annotating Sequence with Count and Zip in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates using `funcy.count` with `zip` to pair elements of a sequence (a string 'abcd') with an increasing sequence of numbers starting from 0. ```python zip(count(), 'abcd') # -> (0, 'a'), (1, 'b'), (2, 'c'), (3, 'd') ``` -------------------------------- ### Taking First N Items with Take in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `funcy.take` to get the first 3 items from different types of sequences: a list, an infinite iterator (`count`), and a string. ```python take(3, [2, 3, 4, 5]) # [2, 3, 4] ``` ```python take(3, count(5)) # [5, 6, 7] ``` ```python take(3, 'ab') # ['a', 'b'] ``` -------------------------------- ### Generating Arithmetic Sequence with Iterate in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `funcy.iterate` with a simple increment function (`inc`) and a starting value (5) to generate an infinite arithmetic sequence. ```python iterate(inc, 5) # -> 5, 6, 7, 8, 9, ... ``` -------------------------------- ### Grouping Command Line Arguments in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `group_values` and `keep` with a regex to process command-line arguments (`sys.argv`), likely extracting key-value pairs starting with `--`. ```Python group_values(keep(r'^--(\w+)=(.+)', sys.argv)) ``` -------------------------------- ### Recognizing Items with keep in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `lkeep` with a dictionary's `get` method to recognize items (colors) in a sequence (`color_names`), filtering out names that are not found (return `None`, which is falsy). ```Python lkeep(COLOR_BY_NAME.get, color_names) ``` -------------------------------- ### Monkey-patching a Django QuerySet method with Funcy Source: https://github.com/suor/funcy/blob/master/docs/objects.rst Illustrates using the `@monkey` decorator to add or replace a method on an existing class or module. This example patches the `get` method of a Django `QuerySet` to implement simple caching for lookups by primary key. ```Python @monkey(QuerySet) def get(self, *args, **kwargs): if not args and list(kwargs) == ['pk']: cache_key = '%s:%d' % (self.model, kwargs['pk']) result = cache.get(cache_key) if result is None: result = get.original(self, *args, **kwargs) cache.set(cache_key, result) return result else: return get.original(self, *args, **kwargs) ``` -------------------------------- ### Using once Decorator for Global Initialization in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Demonstrates using the `@once` decorator on a function (`initialize_cache`) to ensure that the function's body is executed only the first time it is called, suitable for global setup tasks that should not be repeated. ```Python @once def initialize_cache(): conn = some.Connection(...) # ... set up everything ``` -------------------------------- ### Mapping Dictionary Keys with walk_keys in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Provides examples of using `walk_keys` to apply a function to the keys of a dictionary or collection of pairs, preserving the original values. ```Python 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 ``` -------------------------------- ### Splitting Sequence Start with lsplit_by in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates using `lsplit_by` with the `bool` predicate to split an iterator. It yields elements from the start as long as they are truthy (`-2`, `-1`) and returns the remaining elements (`0`, `1`, `2`) as the second part of the tuple, correctly handling the iterator's state. ```Python lsplit_by(bool, iter([-2, -1, 0, 1, 2])) ``` -------------------------------- ### Removing falsy values from a dictionary using compact (Python) Source: https://github.com/suor/funcy/blob/master/docs/primitives.rst Provides an example of using the 'compact' function to remove all falsy values (including None, False, 0, '', etc.) from a dictionary, contrasting it with the more specific 'notnone'. ```Python compact(data_dict) ``` -------------------------------- ### Listing Tree Leaves Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Provides an example of using `ltree_leaves` to list all leaf nodes in a tree structure, specifically demonstrating how to list all descendants of a base class using `type.__subclasses__` as the children and follow function. ```Python ltree_leaves(Base, children=type.__subclasses__, follow=type.__subclasses__) ``` -------------------------------- ### Select Collection Elements with Funcy in Python Source: https://github.com/suor/funcy/blob/master/README.rst Examples of selecting elements or key-value pairs from collections based on a predicate function. `select` filters elements, `select_keys` filters dictionary items by key, and `compact` removes falsy values (like None, 0, ''). ```Python 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} ``` -------------------------------- ### Compose and Transform Functions with Funcy in Python Source: https://github.com/suor/funcy/blob/master/README.rst Examples of functional programming tools for manipulating functions: `partial` for fixing arguments, `curry` for creating curried functions, `compose` for chaining functions, `complement` for negating a predicate, and `all_fn` for checking if all predicates pass. `rpartial` and `rcurry` are right-associative versions. ```Python 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) ``` -------------------------------- ### Processing Lines with Previous Context using with_prev in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Provides an example of using `with_prev` to iterate through lines of text, accessing the current line and the preceding one, useful for tasks like conditional formatting based on the previous element. ```Python for line, prev in with_prev(text.splitlines()): if not prev: print ' ', print line ``` -------------------------------- ### Project Requirements (Python) Source: https://github.com/suor/funcy/blob/master/docs/requirements.txt Specifies the exact versions of Python packages needed for the project. This list is used by package managers like pip to install dependencies. ```Python Sphinx==7.3.7 sphinx-rtd-theme==2.0.0 sphinxcontrib-jquery==4.1 ``` -------------------------------- ### Manipulate Sequences with Funcy in Python Source: https://github.com/suor/funcy/blob/master/README.rst Shows various functions for sequence manipulation, including taking/dropping elements, removing elements, concatenating, flattening, getting distinct elements, splitting, grouping, and partitioning sequences into chunks or pairs. ```Python 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], ... ``` -------------------------------- ### Splitting by Predicate with lsplit in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `lsplit` with a predicate (`re_tester('^_')`) to split the result of `dir(instance)` into two lists: one containing items that match the predicate (private attributes starting with `_`) and one containing items that do not (public attributes). ```Python private, public = lsplit(re_tester('^_'), dir(instance)) ``` -------------------------------- ### Finding Patterns with re_find (Python) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Demonstrates various uses of the re_find function to extract information from strings using regular expressions. Examples show finding simple matches, capturing positional groups, and capturing named groups, illustrating the function's flexible return types based on the regex structure. ```Python # 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) ``` -------------------------------- ### Selecting Dictionary Items by Keys with select_keys in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Provides an example of using `select_keys` to filter a dictionary, keeping only items whose keys satisfy a given predicate function. ```Python is_public = complement(re_tester('^_')) public = select_keys(is_public, instance.__dict__) ``` -------------------------------- ### Using keep with attrgetter in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows an alternative to the generator expression example, using `attrgetter` from the `operator` module as the mapping function passed to `keep`. This achieves the same result of filtering falsy names extracted from `fields`. ```Python keep(attrgetter('name'), fields) ``` -------------------------------- ### Using once_per Decorator for Specific Argument Initialization in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Illustrates using the `@once_per('cls')` decorator to call a method (`_initialize_class`) only once for each unique value of a specified argument (`cls`), useful for class-specific setup within a manager or factory pattern. ```Python class SomeManager(Manager): @once_per('cls') def _initialize_class(self, cls): pre_save.connect(self._pre_save, sender=cls) # ... set up signals, no dups ``` -------------------------------- ### Abstract Control Flow with Funcy Error Handling in Python Source: https://github.com/suor/funcy/blob/master/README.rst Combines multiple decorators (`@ignore`, `@limit_error_rate`, `@retry`) to abstract complex error handling logic. This example shows retrying a function call on specific errors, limiting the rate of errors, and ignoring certain exceptions. ```Python @ignore(ErrorRateExceeded) @limit_error_rate(fails=5, timeout=60) @retry(tries=2, errors=(HttpError, ServiceDown)) def some_unreliable_action(...): "..." ``` -------------------------------- ### Removing Falsy Items with keep in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows the single-argument form of `keep`, which filters out all falsy values directly from the input sequence. This example removes empty lines (which are falsy strings) from the result of `splitlines()`. ```Python keep(description.splitlines()) ``` -------------------------------- ### Accessing Nth Item in Sequence Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using the `nth` function to retrieve the item at a specific index (0-based) from a sequence, specifically showing how to get the 6th line (index 5) from a file by repeatedly calling its `readline` method. ```Python nth(5, repeatedly(open('some_file').readline)) ``` -------------------------------- ### Using wrap_with Decorator (Python) Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Turns a context manager into a decorator. The decorated function will be executed within the context provided by the context manager passed to @wrap_with, ensuring proper setup and teardown (e.g., acquiring and releasing a lock). ```Python @wrap_with(threading.Lock()) def protected_func(...): # ... ``` -------------------------------- ### Structuring User Data using partition in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `partition` with a size of 3 to group user data (id, name, password) and then using a dictionary comprehension to structure it by user id. ```Python {id: (name, password) for id, name, password in partition(3, users)} ``` -------------------------------- ### Sliding Window Average using partition in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates using `partition` with a step of 1 to create a sliding window of size `n` over `data_points`, calculating the average for each window. ```Python [sum(window) / n for window in partition(n, 1, data_points)] ``` -------------------------------- ### Creating Dictionary from Flat List using partition in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `partition` with a size of 2 to group elements from a flat list into pairs, which are then used to create a dictionary. ```Python dict(partition(2, flat_list_of_pairs)) ``` -------------------------------- ### Import Funcy Functions in Python Source: https://github.com/suor/funcy/blob/master/README.rst Demonstrates how to import specific functions from the funcy library into your Python script or interactive session. Replace 'whatever, you, need' with the actual function names you intend to use. ```Python from funcy import whatever, you, need ``` -------------------------------- ### Chunking Sequence with Default Step using chunks in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows the basic usage of the `chunks` function with a size of 2 on a string, demonstrating how it includes the final partial chunk. ```Python chunks(2, 'abcde') # -> 'ab', 'cd', 'e' ``` -------------------------------- ### Run Funcy Tests with Pytest Source: https://github.com/suor/funcy/blob/master/README.rst Executes the Funcy test suite using the pytest framework with the default Python interpreter configured in the environment. ```Shell py.test ``` -------------------------------- ### Pattern Matching with First and Do in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `funcy.first` in combination with a list of condition/action pairs (`TYPE_TO_WIDGET`) to implement a simple pattern matching or dispatch mechanism for selecting a form field widget based on field properties. ```python 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)) ``` -------------------------------- ### Lazy initialization with Funcy's LazyObject Source: https://github.com/suor/funcy/blob/master/docs/objects.rst Shows how to use the `@LazyObject` decorator to defer the initialization of an object until its first attribute access. This is useful for resources that are expensive to create and may not always be needed. ```Python @LazyObject def redis_client(): if isinstance(settings.REDIS, str): return StrictRedis.from_url(settings.REDIS) else: return StrictRedis(**settings.REDIS) ``` -------------------------------- ### Mapping String Characters with walk in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Demonstrates applying a function to each character in a string using `walk`, returning a new string with the mapped characters. ```Python walk(lambda x: x * 2, 'ABC') # -> 'AABBCC' walk(compose(str, ord), 'ABC') # -> '656667' ``` -------------------------------- ### Run Funcy Tests with Tox for Specific Environments Source: https://github.com/suor/funcy/blob/master/README.rst Runs the Funcy test suite using tox for specific Python environments. This allows testing against different Python versions (e.g., py310, pypy3) or linting checks (lint). ```Shell tox -e py310 tox -e pypy3 tox -e lint ``` -------------------------------- ### Defining zip_with using map and zip (Python) Source: https://github.com/suor/funcy/blob/master/TODO.rst This snippet shows a conceptual definition or pseudocode for a 'zip_with' function, illustrating how it could be implemented using the standard 'map' and 'zip' functions, common in Python. ```Python zip_with = map(f, zip(seqs)) ``` -------------------------------- ### Cyclically Decorating Sequence with Cycle and Zip in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `funcy.cycle` to repeatedly cycle through a list of values ('even', 'odd') and pair them with an infinite sequence from `count` using `zip` to decorate numbers with their parity. ```python for n, parity in zip(count(), cycle(['even', 'odd'])): print '%d is %s' % (n, parity) ``` -------------------------------- ### Create Custom Decorators with Funcy in Python Source: https://github.com/suor/funcy/blob/master/README.rst Shows how to easily create custom function decorators using the `@decorator` helper. The decorated function's call information (function, args, kwargs) is passed to the decorator function. ```Python @decorator def log(call): print(call._func.__name__, call._args) return call() ``` -------------------------------- ### Creating Dictionaries with zipdict in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Demonstrates how the `funcy.zipdict` function creates a dictionary by pairing elements from two sequences (keys and values). It stops when the shorter sequence ends. ```python zipdict('abcd', range(4)) ``` ```python zipdict('abc', count()) ``` -------------------------------- ### Using invoke in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Shows how to use `invoke` to call a named method ('find') with specific arguments ('b') on each item in a sequence of objects (strings). It returns a list of the results. ```Python invoke(['abc', 'def', 'b'], 'find', 'b') # ->[1, -1, 0] ``` -------------------------------- ### Using @make_lookuper for resource loading in Python Source: https://github.com/suor/funcy/blob/master/docs/calc.rst Illustrates how `@make_lookuper` can be used to load resources based on arguments, memoize the results, and use the resulting lookup function to access the loaded data. ```python @make_lookuper def translate(lang): return make_list_of_pairs(load_translation_file(lang)) russian_phrases = lmap(translate('ru'), english_phrases) ``` -------------------------------- ### Using once_per_args Decorator for Per-Argument Initialization in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Shows how the `@once_per_args` decorator ensures a function (`initialize_language`) is called only once for each unique combination of its arguments, useful for initializing resources or configurations based on input parameters. ```Python @once_per_args def initialize_language(lang): conf = load_language_conf(lang) # ... set up language ``` -------------------------------- ### Mapping Dictionary Pairs with walk in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Shows how `walk` can be used to map `(key, value)` pairs in a dictionary, effectively transforming both keys and values or swapping them. ```Python swap = lambda k, v: (v, k) walk(swap, {1: 10, 2: 20}) ``` -------------------------------- ### Mapping defaultdict Values with walk_values in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Illustrates the special handling of `defaultdict` by `walk_values`, where values are mapped and the default factory is composed with the mapping function. ```Python d = defaultdict(lambda: 'default', a='hi', b='bye') walk_values(str.upper, d) # -> defaultdict(lambda: 'DEFAULT', a='HI', b='BYE') ``` -------------------------------- ### Chunking Sequence with Custom Step using chunks in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using the `chunks` function with a size of 2 and a step of 4 on a string, showing how it handles overlapping or sparse chunks and includes the final partial chunk. ```Python chunks(2, 4, 'abcde') # -> 'ab', 'e' ``` -------------------------------- ### Mapping Collection Elements with walk in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Illustrates how to use the `walk` function to apply a function to each element of a set or tuple, returning a new collection of the same type. ```Python walk(inc, {1, 2, 3}) # -> {2, 3, 4} walk(inc, (1, 2, 3)) # -> (2, 3, 4) ``` -------------------------------- ### Using fallback Function for Chained Approaches in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Demonstrates using the `fallback` function to define a sequence of callable "approaches", each with optional specific exceptions that trigger falling back to the next approach, until one succeeds or the list is exhausted, providing resilience. ```Python fallback( (partial(send_mail, ADMIN_EMAIL, message), SMTPException), partial(log.error, message), # Handle any Exception (raiser(FeedbackError, "Failed"), ()) # Handle nothing ) ``` -------------------------------- ### Splitting Sequence by Type using isa - Python Source: https://github.com/suor/funcy/blob/master/docs/types.rst Demonstrates how to use the `isa` function with `lsplit` to partition a sequence (`values`) into two lists (`labels`, `ids`) based on whether elements are of type `str`. ```Python labels, ids = lsplit(isa(str), values) ``` -------------------------------- ### Parsing Key-Value Pairs with re_iter (Python) Source: https://github.com/suor/funcy/blob/master/docs/strings.rst Illustrates a concise method using re_iter to find all occurrences of a key=value pattern in a string and convert the results directly into a Python dictionary. ```Python # A fast and dirty way to parse ini section into dict dict(re_iter('(\w+)=(\w+)', ini_text)) ``` -------------------------------- ### Flattening Lines with mapcat in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `mapcat` to apply `str.splitlines` to each item in `bunch_of_texts` and then concatenate all the resulting lists of lines into a single flat list. ```Python mapcat(str.splitlines, bunch_of_texts) ``` -------------------------------- ### Applying Flattening to Product of Sequences Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to combine `lmap`, `lcat`, and `itertools.product` to flatten the results of a Cartesian product of sequences, effectively performing a brace expansion-like operation. ```Python terms = [['a', 'b'], ['t', 'pq'], ['x']] lmap(lcat, product(*terms)) ``` -------------------------------- ### Debugging with tap function in Python Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Demonstrates using the `tap` function within a generator expression and a dictionary comprehension to print intermediate values for debugging without interrupting the flow. ```Python fields = (f for f in fields_for(category) if section in tap(tap(f).sections)) ``` ```Python squares = {tap(x, 'x'): tap(x * x, 'x^2') for x in [3, 4]} ``` -------------------------------- ### Building Path with takewhile in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how `takewhile` can be used with the `bool` predicate and `iterate` to traverse a tree structure from a given `node` up to the root. It yields nodes as long as they are truthy, effectively building the path. ```Python takewhile(bool, iterate(attrgetter('parent'), node)) ``` -------------------------------- ### Creating List of Objects with Repeatedly in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates using `funcy.repeatedly` with a type constructor like `list` to generate a sequence of 'n' freshly-created objects of that type. ```python repeatedly(list, n) ``` -------------------------------- ### Merging Default Options with User Options in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Demonstrates using the `merge` function to combine a dictionary of default options with a dictionary of user-provided options, where user options override defaults. ```Python def utility(**options): defaults = {...} options = merge(defaults, options) ... ``` -------------------------------- ### Using @make_lookuper with arguments in Python Source: https://github.com/suor/funcy/blob/master/docs/calc.rst Shows how `@make_lookuper` creates separate lookup tables for each combination of arguments passed to the decorated function, enabling the creation of specialized lookup functions on demand. ```python @make_lookuper def function_lookup(f): return {x: f(x) for x in range(100)} fast_sin = function_lookup(math.sin) fast_cos = function_lookup(math.cos) ``` -------------------------------- ### Logging function calls with print_calls/log_calls in Python Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Shows how to use `print_calls` as a key function in `sorted` and how to use `@log_calls` and `@log_errors` as decorators to log function entry, exit, arguments, results, and errors. ```Python sorted_fields = sorted(fields, key=print_calls(lambda f: f.order)) ``` ```Python @log_calls(log.info, errors=False) @log_errors(log.exception) def some_suspicious_function(...): # ... return result ``` -------------------------------- ### Dropping First N Items with Drop in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `funcy.drop` to skip the first 3 items in different sequences, returning an iterator for the remaining elements. ```python drop(3, [2, 3, 4, 5]) # iter([5]) ``` ```python drop(3, count(5)) # count(8) ``` ```python drop(3, 'ab') # empty iterator ``` -------------------------------- ### Filtering None values using isnone and lsplit_by (Python) Source: https://github.com/suor/funcy/blob/master/docs/primitives.rst Demonstrates using the 'isnone' function with 'lsplit_by' to partition a list, separating leading None values from the rest of the data. ```Python _ data = lsplit_by(isnone, dirty_data) ``` -------------------------------- ### Generating Random Numbers with Repeatedly in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `funcy.repeatedly` with `random.random` to generate a sequence of 10 random floating-point numbers by repeatedly calling the function. ```python repeatedly(random.random, 10) ``` -------------------------------- ### Creating OrderedDict Sorted by Value with Second in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates using `funcy.second` as the key for sorting dictionary items and then passing the sorted items to `OrderedDict` to create a dictionary ordered by its values. ```python OrderedDict(sorted(plain_dict.items(), key=second)) ``` -------------------------------- ### Using all with isa Predicate in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Illustrates an alternative way to check if all elements in a sequence (`seq`) are integers using the `all` function with the `isa` predicate. ```Python they_are_ints = all(isa(int), seq) ``` -------------------------------- ### Creating List/Tuple with Repeat Item in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates alternative Python syntax using multiplication to create a list or tuple containing the same item repeated 'n' times, which can be simpler than using `repeat` when an iterator is not needed. ```python [item] * n ``` ```python (item,) * n ``` -------------------------------- ### Abstract Control Flow with Funcy Silent in Python Source: https://github.com/suor/funcy/blob/master/README.rst Demonstrates using `silent` to wrap a function call within a larger operation. If the wrapped function raises an exception, `silent` catches it and returns `None` instead of propagating the error. ```Python walk_values(silent(int), {'a': '1', 'b': 'no'}) # => {'a': 1, 'b': None} ``` -------------------------------- ### Grouping Posts by Tags with group_by_keys in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how `group_by_keys` can be used with `attrgetter('tags')` to group a sequence of `posts`. Assuming each post object has a `tags` attribute (likely a list or set), this function groups posts by each individual tag they possess, creating a mapping from tag to a list of posts having that tag. ```Python posts_by_tag = group_by_keys(attrgetter('tags'), posts) ``` -------------------------------- ### Finding First Match with keep and first in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates combining the iterator version of `keep` with `first` to efficiently find the first item in a sequence (`color_name_candidates`) that matches a recognition criteria (lookup in `COLOR_BY_NAME`), stopping iteration once found. ```Python first(keep(COLOR_BY_NAME.get, color_name_candidates)) ``` -------------------------------- ### Using all with Predicate Function in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Shows using the `all` function with a predicate function (`even`) and a sequence (`seq`) to check if the predicate holds true for every element in the sequence. ```Python they_are_even = all(even, seq) ``` -------------------------------- ### Using any with Extended Predicate in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Demonstrates using the `any` function with an extended predicate (a regular expression `r'needle'`) to check if any string in `haystack_strings` matches the pattern. ```Python any(r'needle', haystack_strings) ``` -------------------------------- ### Using all with Generator Expression in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Demonstrates using the `all` function with a generator expression that applies a predicate (`is_instance(n, int)`) to each element in a sequence (`seq`) to check if all elements satisfy the condition. ```Python they_are_ints = all(is_instance(n, int) for n in seq) ``` -------------------------------- ### Debug with Funcy Tap in Python Source: https://github.com/suor/funcy/blob/master/README.rst Illustrates using the `tap` function to inspect intermediate values within an expression without altering the expression's result. `tap` prints the value and returns it, making it useful for debugging pipelines or comprehensions. ```Python squares = {tap(x, 'x'): tap(x * x, 'x^2') for x in [3, 4]} # x: 3 # x^2: 9 # ... ``` -------------------------------- ### Extracting Values Sorted by Key with Second and Map in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `funcy.second` with `map` and `sorted` on dictionary items to extract the values from a dictionary, ordered by their corresponding keys. ```python map(second, sorted(some_dict.items())) ``` -------------------------------- ### Extracting First Paragraph with takewhile in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `takewhile` with a predicate (`re_tester(r'\S')`) to yield lines from `text.splitlines()` as long as they contain non-whitespace characters, effectively extracting the first paragraph which is typically followed by an empty line. ```Python takewhile(re_tester(r'\S'), text.splitlines()) ``` -------------------------------- ### Extracting Data with keep in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `lkeep` with a function (`re_finder`) to extract specific data (numbers) from a sequence (`words`), filtering out items where the extraction fails (returns falsy). ```Python lkeep(re_finder(r'\d+'), words) ``` -------------------------------- ### Basic usage of @make_lookuper in Python Source: https://github.com/suor/funcy/blob/master/docs/calc.rst Demonstrates the basic use of `@make_lookuper` to transform a function that returns a dictionary or sequence of pairs into a lookup function that raises `LookupError` for missing keys. ```python @make_lookuper def city_location(): return {row['city']: row['location'] for row in fetch_city_locations()} ``` -------------------------------- ### Merge Collections with Funcy in Python Source: https://github.com/suor/funcy/blob/master/README.rst Shows different ways to merge collections (dicts, sets, lists, tuples, iterators, strings) using funcy. `merge` combines multiple collections, `join` combines a list of collections, and `merge_with` allows specifying a function to handle value conflicts in dicts. ```Python merge(coll1, coll2, coll3, ...) join(colls) merge_with(sum, dict1, dict2, ...) ``` -------------------------------- ### Timing iterable processing with log_iter_durations/print_iter_durations in Python Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Demonstrates wrapping an iterable with `print_iter_durations` to log the time taken to process each individual item during iteration. ```Python for item in print_iter_durations(seq, label='hard work'): do_smth(item) ``` -------------------------------- ### Generating Fibonacci Sequence with Iterate and Map in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates a more complex use of `funcy.iterate` to generate the Fibonacci sequence. It uses a step function that calculates the next pair in the sequence and then `map` with `first` to extract the first element of each pair. ```python step = lambda p: (p[1], p[0] + p[1]) map(first, iterate(step, (0, 1))) # -> 0, 1, 1, 2, 3, 5, 8, ... ``` -------------------------------- ### Using retry Decorator for Basic Retries in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Demonstrates applying the `@retry` decorator to a function (`download_image`) to automatically retry its execution up to a specified number of times (`3`) if a particular exception (`HttpError`) occurs, useful for unreliable operations. ```Python @retry(3, errors=HttpError) def download_image(url): # ... make http request return image ``` -------------------------------- ### Abstract Control Flow with Funcy Suppress in Python Source: https://github.com/suor/funcy/blob/master/README.rst Shows using the `suppress` context manager to ignore specified exceptions within a block of code. If an exception listed in `suppress` occurs, it is caught and execution continues after the `with` block. ```Python with suppress(OSError): os.remove('some.file') ``` -------------------------------- ### Flipping Dictionary Keys and Values with flip in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Illustrates the `funcy.flip` function, which swaps keys and values in a mapping or a sequence of pairs, preserving the collection type. ```python flip(OrderedDict(['aA', 'bB'])) ``` -------------------------------- ### Transform Collections with Funcy Walk in Python Source: https://github.com/suor/funcy/blob/master/README.rst Illustrates using `walk`, `walk_keys`, and `walk_values` to transform collection elements while preserving the original collection type. `walk` applies a function to key-value pairs (or elements), `walk_keys` transforms keys, and `walk_values` transforms values. ```Python 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} ``` -------------------------------- ### Timing function execution with log_durations/print_durations in Python Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Shows how to use `@log_durations` as a decorator to measure function execution time, `print_durations` as a context manager to time code blocks, and how to set a `threshold` to only log durations exceeding a certain time. ```Python @log_durations(logging.info) def do_hard_work(n): samples = range(n) # ... ``` ```Python with print_durations('Creating models'): Model.objects.create(...) # ... ``` ```Python @log_durations(logging.warning, threshold=0.5) def make_query(sql, params): # ... ``` -------------------------------- ### Finding First Failed Validation Rule with First in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates using `funcy.first` with a generator expression to find and return the text message of the first validation rule that fails for a given instance. ```python fail = first(rule.text for rule in rules if not rule.test(instance)) ``` -------------------------------- ### Specify whatever dependency Source: https://github.com/suor/funcy/blob/master/test_requirements.txt Specifies the required version '0.7' for the 'whatever' package without any Python version condition. ```Python whatever==0.7 ``` -------------------------------- ### Debug with Funcy Logging Decorators in Python Source: https://github.com/suor/funcy/blob/master/README.rst Shows using `@log_calls` and `@log_errors` decorators to automatically log function calls and exceptions. `@log_calls` logs function entry/exit, and `@log_errors` logs exceptions that occur within the function. ```Python @log_calls(log.info, errors=False) @log_errors(log.exception) def some_suspicious_function(...): "..." ``` -------------------------------- ### Filtering Dictionary Pairs with select in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Shows how `select` can filter dictionary items based on a predicate applied to `(key, value)` pairs, returning a new dictionary with matching items. ```Python select(lambda k, v: k == v, {1: 1, 2: 3}) # -> {1: 1} ``` -------------------------------- ### Grouping Items by Length with group_by in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Demonstrates using `group_by` with the `len` function to group elements of a list (`['a', 'ab', 'b']`) based on their length. It returns a `defaultdict(list)` where keys are lengths and values are lists of elements with that length. ```Python stats = group_by(len, ['a', 'ab', 'b']) ``` -------------------------------- ### Mapping Dictionary Values with walk_values in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Shows common use cases for `walk_values`, applying a function to the values of a dictionary or collection of pairs to clean or transform them. ```Python clean_values = walk_values(int, form_values) sorted_groups = walk_values(sorted, groups) ``` -------------------------------- ### Using none with Extended Predicate in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Illustrates using the `none` function with an extended predicate (checking for the presence of a space character `' '`) and a sequence (`names`) to check if none of the elements contain a space. ```Python assert none(' ', names), "..." ``` -------------------------------- ### Extracting Regex Matches with mapcat in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how `mapcat` can be used with a function like `re_all` (presumably returning a list of matches) to extract all occurrences of a pattern (numbers `\d+`) from each string in `bunch_of_strings` and collect them into a single flat list. ```Python mapcat(partial(re_all, r'\d+'), bunch_of_strings) ``` -------------------------------- ### Using joining Decorator with Bytes Separator (Python) Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Demonstrates using the @joining decorator with a bytes separator. Similar to the string version, it collects yielded items, converts them, and joins them, but results in a bytes string. ```Python @joining(b' ') def car_desc(self): yield self.year_made # ... ``` -------------------------------- ### Using @memoize decorator in Python Source: https://github.com/suor/funcy/blob/master/docs/calc.rst Demonstrates the basic application of the `@memoize` decorator to cache function results. It includes handling exceptions and using `memoize.skip` to prevent caching for specific outcomes. ```python @memoize # Omitting parentheses is ok def ip_to_city(ip): try: return request_city_from_slow_service(ip) except NotFound: return None # return None and memoize it except Timeout: raise memoize.skip(CITY) # return CITY, but don't memoize it ``` -------------------------------- ### Debug with Funcy Print Durations in Python Source: https://github.com/suor/funcy/blob/master/README.rst Uses the `print_durations` context manager to measure and print the execution time of a block of code. It takes a label string that is included in the output. ```Python with print_durations('Creating models'): Model.objects.create(...) # ... # 10.2 ms in Creating models ``` -------------------------------- ### Calculating Length Histogram using count_by in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `count_by` with the `len` function as the key to calculate a histogram of word lengths from a list of words. ```Python count_by(len, words) ``` -------------------------------- ### Using key_func with @cache in Python Source: https://github.com/suor/funcy/blob/master/docs/calc.rst Shows how to use a custom `key_func` with the `@cache` decorator to customize the cache key generation, for instance, to exclude sensitive or irrelevant arguments from the key. ```python # Do not use token in cache key @cache(60 * 60, key_func=lambda query, token=None: query) def api_call(query, token=None): # ... ``` -------------------------------- ### Splitting URLs by Predicate with lsplit in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows another use case for `lsplit`, splitting a sequence of URLs (`urls`) into two lists based on whether they match a regex predicate (`r'^http://'`), separating absolute URLs from relative ones. ```Python absolute, relative = lsplit(r'^http://', urls) ``` -------------------------------- ### Using suppress Context Manager in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Illustrates using the `suppress` context manager to wrap a block of code (`make_http_request`) and ignore specific exceptions (`HttpError`) that might occur within that block, preventing them from propagating. ```Python with suppress(HttpError): # Assume this request can fail, and we are ok with it make_http_request() ``` -------------------------------- ### Skipping Leading Whitespace with dropwhile in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates using `dropwhile` with a predicate (`re_tester('^\s*$')`) to skip lines from `text_lines` that consist only of whitespace (or are empty) at the beginning of the sequence, yielding the first non-whitespace line and all subsequent lines. ```Python dropwhile(re_tester('^\s*$'), text_lines) ``` -------------------------------- ### Iterating Tree Nodes Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Shows how to use `tree_nodes` to iterate over all nodes in a tree hierarchy, using class subclassing and `type.__subclasses__` to traverse all classes in a hierarchy. ```Python tree_nodes(Base, children=type.__subclasses__, follow=type.__subclasses__) ``` -------------------------------- ### Finding First Element Exceeding Threshold using sums and first in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates combining `sums` (for cumulative totals), `enumerate` (for index), and `first` to find the index of the first element in `straw_weights` whose cumulative sum exceeds `camel_toughness`. ```Python first(i for i, total in enumerate(sums(straw_weights)) if total > camel_toughness) ``` -------------------------------- ### Using key_func with @memoize in Python Source: https://github.com/suor/funcy/blob/master/docs/calc.rst Illustrates how to provide a custom `key_func` to the `@memoize` decorator to control how cache keys are generated, useful for handling unhashable arguments or ignoring specific parameters. ```python @memoize(key_func=lambda obj, verbose=None: obj.key) def do_things(obj, verbose=False): # ... ``` -------------------------------- ### Tracing errors with log_errors/print_errors in Python Source: https://github.com/suor/funcy/blob/master/docs/debug.rst Illustrates combining `@log_errors` with `@ignore` to trace errors in a function that might raise exceptions, and using `print_errors` as a context manager to log errors within a block of code. ```Python @ignore(...) @log_errors(logging.warning) def guess_user_id(username): initial = first_guess(username) # ... ``` ```Python with print_errors('initialization', stack=False): load_this() load_that() # ... ``` -------------------------------- ### Filtering Dictionaries by Conditions with where/lwhere in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Demonstrates `funcy.where` and `funcy.lwhere`, which filter a sequence of dictionaries to return those matching all key-value pairs in a condition dictionary. `where` returns an iterator, `lwhere` returns a list. ```python lwhere(plays, author="Shakespeare", year=1611) ``` ```python first(where(plays, author="Shakespeare")) ``` -------------------------------- ### Abstract Control Flow with Funcy Once in Python Source: https://github.com/suor/funcy/blob/master/README.rst Uses the `@once` decorator to ensure that a function is called at most once, regardless of how many times it is invoked. Subsequent calls after the first will return the result of the initial call. ```Python @once def initialize(): "..." ``` -------------------------------- ### Grouping Sentences by Words with group_by_keys in Python Source: https://github.com/suor/funcy/blob/master/docs/seqs.rst Illustrates another use case for `group_by_keys`, grouping a sequence of `sentences`. Using `str.split` as the key extractor means each sentence is split into words, and the function groups sentences by each word they contain, creating a mapping from word to a list of sentences containing that word. ```Python sentences_with_word = group_by_keys(str.split, sentences) ``` -------------------------------- ### Using silent Decorator for Data Cleaning in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Demonstrates using the `silent` decorator to wrap type conversions (`int`) to ignore exceptions like `ValueError` when processing potentially invalid input from `request.GET` or `request.GET.getlist`, returning `None` on error. ```Python brand_id = silent(int)(request.GET['brand_id']) ids = keep(silent(int), request.GET.getlist('id')) ``` -------------------------------- ### Using nullcontext Context Manager in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Shows how `nullcontext` can be used as a placeholder context manager that does nothing, allowing conditional application of a real context manager (`op_thread_lock`) within a `with` statement without needing an `if/else` structure for the `with` itself. ```Python ctx = nullcontext() if threads: ctx = op_thread_lock with ctx: # ... do stuff ``` -------------------------------- ### Using raiser Function for Property Patching in Python Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Demonstrates using the `raiser` function to create a callable that raises a specified exception (or a default `Exception` with a message string) when invoked, useful here for patching a property to indicate it should not be accessed. ```Python mocker.patch('mod.Class.propname', property(raiser("Shouldn't be called"))) ``` -------------------------------- ### Using joining Decorator with String Separator (Python) Source: https://github.com/suor/funcy/blob/master/docs/flow.rst Transforms a generator-returning function into one that returns a single string. The decorator collects all items yielded by the generator, converts them to strings, and joins them using the specified string separator. ```Python @joining(', ') def car_desc(self): yield self.year_made if self.engine_volume: yield '%s cc' % self.engine_volume if self.transmission: yield self.get_transmission_display() if self.gear: yield self.get_gear_display() # ... ``` -------------------------------- ### Using itervalues on a Set in Python Source: https://github.com/suor/funcy/blob/master/docs/colls.rst Demonstrates using `itervalues` on a set (`{1, 2, 42}`). For sets, `itervalues` yields the elements themselves. ```Python list(itervalues({1, 2, 42})) # -> [1, 42, 2] ```