CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pydash

A comprehensive Python utility library for functional programming inspired by JavaScript's Lo-Dash

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities Module

The Utilities module provides 38 general utility functions and helpers for common programming tasks. These functions include function creation utilities, value generation, random operations, conditional logic, and various helper functions.

Function Creation Utilities

constant

def constant(value: Any) -> Callable

Creates a function that returns value.

Parameters:

  • value (Any): Value to return from new function.

Returns:

  • Callable: New constant function.

Example:

from pydash import constant

always_true = constant(True)
always_true()  # True
always_true(1, 2, 3)  # True (ignores arguments)

get_pi = constant(3.14159)
get_pi()  # 3.14159

identity

def identity(value: Any) -> Any

Returns the first argument it receives.

Parameters:

  • value (Any): Any value.

Returns:

  • Any: value.

Example:

from pydash import identity

identity('hello')  # 'hello'
identity([1, 2, 3])  # [1, 2, 3]

# Useful as a default function
list(map(identity, [1, 2, 3]))  # [1, 2, 3]

iteratee

def iteratee(func: Any = None) -> Callable

Creates an iteratee function from func. This function is used internally by many pydash methods.

Parameters:

  • func (Any, optional): Value to convert to an iteratee.

Returns:

  • Callable: New iteratee function.

Example:

from pydash import iteratee

# Function iteratee
func_iter = iteratee(lambda x: x * 2)
func_iter(5)  # 10

# Property iteratee
prop_iter = iteratee('name')
prop_iter({'name': 'John'})  # 'John'

# Matches iteratee
match_iter = iteratee({'age': 25})
match_iter({'name': 'John', 'age': 25})  # True

matches

def matches(source: Any) -> Callable

Creates a function that performs a partial deep comparison between a given object and source, returning True if the given object has equivalent property values, else False.

Parameters:

  • source (Any): Object of property values to match.

Returns:

  • Callable: New predicate function.

Example:

from pydash import matches, filter_

is_user_active = matches({'active': True, 'status': 'online'})

users = [
    {'name': 'John', 'active': True, 'status': 'online'},
    {'name': 'Jane', 'active': False, 'status': 'offline'},
    {'name': 'Bob', 'active': True, 'status': 'online'}
]

active_users = filter_(users, is_user_active)
# [{'name': 'John', 'active': True, 'status': 'online'}, 
#  {'name': 'Bob', 'active': True, 'status': 'online'}]

matches_property

def matches_property(path: Union[str, List], src_value: Any) -> Callable

Creates a function that compares the value at path of a given object to src_value.

Parameters:

  • path (Union[str, List]): Path of the property to get.
  • src_value (Any): Value to match.

Returns:

  • Callable: New predicate function.

Example:

from pydash import matches_property, filter_

is_adult = matches_property('age', 18)
has_admin_role = matches_property('roles[0]', 'admin')

users = [
    {'name': 'John', 'age': 25, 'roles': ['admin', 'user']},
    {'name': 'Jane', 'age': 17, 'roles': ['user']},
    {'name': 'Bob', 'age': 30, 'roles': ['user']}
]

adults = filter_(users, lambda u: u['age'] >= 18)
admins = filter_(users, has_admin_role)

method

def method(path: Union[str, List], *args: Any, **kwargs: Any) -> Callable

Creates a function that invokes the method at path of a given object.

Parameters:

  • path (Union[str, List]): Path of the method to invoke.
  • args (*Any): Arguments to invoke the method with.
  • kwargs (**Any): Keyword arguments to invoke the method with.

Returns:

  • Callable: New invoker function.

Example:

from pydash import method, map_

upper_method = method('upper')
split_comma = method('split', ',')

strings = ['hello', 'world', 'foo,bar,baz']
map_(strings[:2], upper_method)  # ['HELLO', 'WORLD']
split_comma('a,b,c')  # ['a', 'b', 'c']

method_of

def method_of(obj: Any, *args: Any, **kwargs: Any) -> Callable

Creates a function that invokes the method at a given path of obj.

Parameters:

  • obj (Any): Object to query.
  • args (*Any): Arguments to invoke the method with.
  • kwargs (**Any): Keyword arguments to invoke the method with.

Returns:

  • Callable: New invoker function.

Example:

from pydash import method_of

string_obj = 'hello world'
get_char = method_of(string_obj)

get_char('__getitem__', 0)  # 'h'
get_char('upper')  # 'HELLO WORLD'

noop

def noop(*args: Any, **kwargs: Any) -> None

A function that returns None regardless of the arguments it receives.

Parameters:

  • args (*Any): Any arguments (ignored).
  • kwargs (**Any): Any keyword arguments (ignored).

Returns:

  • None: Always returns None.

Example:

from pydash import noop

noop()  # None
noop(1, 2, 3)  # None
noop(a=1, b=2)  # None

# Useful as a default callback
def process_data(data, callback=noop):
    result = transform(data)
    callback(result)  # Safe to call even if no callback provided
    return result

property_

def property_(path: Union[str, List]) -> Callable

Creates a function that returns the value at path of a given object.

Parameters:

  • path (Union[str, List]): Path of the property to get.

Returns:

  • Callable: New accessor function.

Example:

from pydash import property_, map_

get_name = property_('name')
get_nested = property_('user.profile.email')

users = [
    {'name': 'John', 'age': 25},
    {'name': 'Jane', 'age': 30}
]

names = map_(users, get_name)  # ['John', 'Jane']

# With nested properties
data = {'user': {'profile': {'email': 'john@example.com'}}}
get_nested(data)  # 'john@example.com'

property_of

def property_of(obj: Any) -> Callable

Creates a function that returns the value at a given path of obj.

Parameters:

  • obj (Any): Object to query.

Returns:

  • Callable: New accessor function.

Example:

from pydash import property_of

user = {'name': 'John', 'profile': {'email': 'john@example.com'}}
get_from_user = property_of(user)

get_from_user('name')  # 'John'
get_from_user('profile.email')  # 'john@example.com'

Value Generation and Random Functions

now

def now() -> int

Returns the timestamp in milliseconds of the current time.

Parameters: None

Returns:

  • int: Current timestamp in milliseconds.

Example:

from pydash import now

timestamp = now()  # e.g., 1634567890123

random

def random(lower: Union[int, float] = 0, upper: Union[int, float] = 1, floating: bool = None) -> Union[int, float]

Produces a random number between the inclusive lower and upper bounds.

Parameters:

  • lower (Union[int, float]): Lower bound. Defaults to 0.
  • upper (Union[int, float]): Upper bound. Defaults to 1.
  • floating (bool, optional): Specify returning a floating-point number.

Returns:

  • Union[int, float]: Random number.

Example:

from pydash import random

random(0, 5)  # e.g., 3
random(1.2, 5.2)  # e.g., 3.7
random(0, 1, True)  # e.g., 0.8234

range_

def range_(start: int = 0, stop: int = None, step: int = 1) -> List[int]

Creates a list of numbers progressing from start up to, but not including, stop.

Parameters:

  • start (int): Start of the range. Defaults to 0.
  • stop (int, optional): End of the range.
  • step (int): Increment between numbers. Defaults to 1.

Returns:

  • List[int]: List of numbers.

Example:

from pydash import range_

range_(4)  # [0, 1, 2, 3]
range_(1, 5)  # [1, 2, 3, 4]
range_(0, 20, 5)  # [0, 5, 10, 15]
range_(0, -4, -1)  # [0, -1, -2, -3]

range_right

def range_right(start: int = 0, stop: int = None, step: int = 1) -> List[int]

Like range_ except that it populates values in descending order.

Parameters:

  • start (int): Start of the range. Defaults to 0.
  • stop (int, optional): End of the range.
  • step (int): Increment between numbers. Defaults to 1.

Returns:

  • List[int]: List of numbers in descending order.

Example:

from pydash import range_right

range_right(4)  # [3, 2, 1, 0]
range_right(1, 5)  # [4, 3, 2, 1]

times

def times(n: int, iteratee: Callable = None) -> List[Any]

Invokes the iteratee n times, returning a list of the results of each invocation.

Parameters:

  • n (int): Number of times to invoke iteratee.
  • iteratee (Callable, optional): Function invoked per iteration.

Returns:

  • List[Any]: List of results.

Example:

from pydash import times

times(3)  # [0, 1, 2]
times(4, lambda i: i * i)  # [0, 1, 4, 9]
times(3, lambda: 'hello')  # ['hello', 'hello', 'hello']

unique_id

def unique_id(prefix: str = '') -> str

Generates a unique ID. If prefix is provided, the ID is prefixed with it.

Parameters:

  • prefix (str): Value to prefix the ID with. Defaults to ''.

Returns:

  • str: Unique ID.

Example:

from pydash import unique_id

unique_id()  # '1'
unique_id('contact_')  # 'contact_2'
unique_id('user_')  # 'user_3'

Stub Functions

stub_dict

def stub_dict() -> Dict

Returns a new empty dictionary.

Parameters: None

Returns:

  • Dict: Empty dictionary.

Example:

from pydash import stub_dict

stub_dict()  # {}

stub_false

def stub_false() -> bool

Returns False.

Parameters: None

Returns:

  • bool: False.

Example:

from pydash import stub_false

stub_false()  # False

stub_list

def stub_list() -> List

Returns a new empty list.

Parameters: None

Returns:

  • List: Empty list.

Example:

from pydash import stub_list

stub_list()  # []

stub_string

def stub_string() -> str

Returns an empty string.

Parameters: None

Returns:

  • str: Empty string.

Example:

from pydash import stub_string

stub_string()  # ''

stub_true

def stub_true() -> bool

Returns True.

Parameters: None

Returns:

  • bool: True.

Example:

from pydash import stub_true

stub_true()  # True

Value Testing and Conversion

attempt

def attempt(func: Callable, *args: Any, **kwargs: Any) -> Any

Attempts to invoke func, returning either the result or the caught error object.

Parameters:

  • func (Callable): Function to attempt.
  • args (*Any): Arguments to invoke func with.
  • kwargs (**Any): Keyword arguments to invoke func with.

Returns:

  • Any: Function result or error object.

Example:

from pydash import attempt, is_error

# Successful execution
result = attempt(int, '42')  # 42

# Failed execution
result = attempt(int, 'invalid')
is_error(result)  # True

default_to

def default_to(value: Any, default_value: Any) -> Any

Checks value to determine whether a default value should be returned in its place. The default_value is returned if value is None or NaN.

Parameters:

  • value (Any): Value to check.
  • default_value (Any): Default value.

Returns:

  • Any: value or default_value.

Example:

from pydash import default_to

default_to(1, 10)  # 1
default_to(None, 10)  # 10
default_to(float('nan'), 10)  # 10

default_to_any

def default_to_any(value: Any, *default_values: Any) -> Any

Like default_to except that it accepts multiple default values and returns the first non-nullish value.

Parameters:

  • value (Any): Value to check.
  • default_values (*Any): Default values to check.

Returns:

  • Any: First non-nullish value.

Example:

from pydash import default_to_any

default_to_any(None, None, 'default')  # 'default'
default_to_any(1, 2, 3)  # 1
default_to_any(None, 2, 3)  # 2

to_path

def to_path(value: Any) -> List[Any]

Converts value to a property path array.

Parameters:

  • value (Any): Value to convert.

Returns:

  • List[Any]: Property path array.

Example:

from pydash import to_path

to_path('a.b.c')  # ['a', 'b', 'c']
to_path('a[0].b.c')  # ['a', 0, 'b', 'c']
to_path(['a', 'b', 'c'])  # ['a', 'b', 'c']

Conditional and Control Flow

cond

def cond(pairs: List[Tuple[Callable, Callable]]) -> Callable

Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy.

Parameters:

  • pairs (List[Tuple[Callable, Callable]]): Predicate-function pairs.

Returns:

  • Callable: New composite function.

Example:

from pydash import cond

func = cond([
    [lambda x: x == 0, lambda x: 'zero'],
    [lambda x: x % 2 == 1, lambda x: 'odd'],
    [lambda x: x % 2 == 0, lambda x: 'even']
])

func(0)  # 'zero'
func(1)  # 'odd'
func(2)  # 'even'

conforms

def conforms(source: Dict[str, Callable]) -> Callable

Creates a function that invokes the predicate properties of source with the corresponding property values of a given object, returning True if all predicates return truthy, else False.

Parameters:

  • source (Dict[str, Callable]): Object of predicate properties.

Returns:

  • Callable: New predicate function.

Example:

from pydash import conforms, filter_

validator = conforms({
    'age': lambda x: x >= 18,
    'name': lambda x: len(x) >= 2
})

users = [
    {'name': 'John', 'age': 25},
    {'name': 'J', 'age': 17},
    {'name': 'Jane', 'age': 30}
]

valid_users = filter_(users, validator)  # [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}]

conforms_to

def conforms_to(obj: Any, source: Dict[str, Callable]) -> bool

Checks if obj conforms to source by invoking the predicate properties of source with the corresponding property values of obj.

Parameters:

  • obj (Any): Object to check.
  • source (Dict[str, Callable]): Object of predicate properties.

Returns:

  • bool: True if obj conforms, else False.

Example:

from pydash import conforms_to

user = {'name': 'John', 'age': 25}
rules = {'age': lambda x: x >= 18, 'name': lambda x: len(x) >= 2}

conforms_to(user, rules)  # True

over_every

def over_every(*predicates: Callable) -> Callable

Creates a function that checks if all of the predicates return truthy when invoked with the arguments it receives.

Parameters:

  • predicates (*Callable): Predicates to check.

Returns:

  • Callable: New predicate function.

Example:

from pydash import over_every

is_positive_even = over_every(lambda x: x > 0, lambda x: x % 2 == 0)
is_positive_even(4)  # True
is_positive_even(-2)  # False
is_positive_even(3)  # False

over_some

def over_some(*predicates: Callable) -> Callable

Creates a function that checks if any of the predicates return truthy when invoked with the arguments it receives.

Parameters:

  • predicates (*Callable): Predicates to check.

Returns:

  • Callable: New predicate function.

Example:

from pydash import over_some

is_string_or_number = over_some(
    lambda x: isinstance(x, str),
    lambda x: isinstance(x, (int, float))
)

is_string_or_number('hello')  # True
is_string_or_number(42)  # True
is_string_or_number([])  # False

over

def over(*iteratees: Callable) -> Callable

Creates a function that invokes iteratees with the arguments it receives and returns their results.

Parameters:

  • iteratees (*Callable): Iteratees to invoke.

Returns:

  • Callable: New function.

Example:

from pydash import over

func = over(max, min, len)
func([1, 2, 3, 4, 5])  # [5, 1, 5]

Function Enhancement Utilities

memoize

def memoize(func: Callable, resolver: Callable = None) -> Callable

Creates a memoized version of func which caches the result of function calls.

Parameters:

  • func (Callable): Function to memoize.
  • resolver (Callable, optional): Function to resolve the cache key.

Returns:

  • Callable: Memoized function.

Example:

from pydash import memoize

@memoize
def expensive_function(n):
    print(f"Computing for {n}")
    return n * n

expensive_function(5)  # "Computing for 5", returns 25
expensive_function(5)  # Returns 25 (cached, no print)

nth_arg

def nth_arg(n: int = 0) -> Callable

Creates a function that gets the argument at index n. If n is negative, the nth argument from the end is returned.

Parameters:

  • n (int): Index of argument to return. Defaults to 0.

Returns:

  • Callable: New function.

Example:

from pydash import nth_arg

first_arg = nth_arg(0)
second_arg = nth_arg(1)
last_arg = nth_arg(-1)

first_arg('a', 'b', 'c')  # 'a'
second_arg('a', 'b', 'c')  # 'b'
last_arg('a', 'b', 'c')  # 'c'

result

def result(obj: Any, path: Union[str, List], default: Any = None) -> Any

Resolves the value of property path on object. If the resolved value is a function, it's invoked with the this binding of its parent object and its result is returned.

Parameters:

  • obj (Any): Object to query.
  • path (Union[str, List]): Path of the property to resolve.
  • default (Any): Value returned if the resolved value is None.

Returns:

  • Any: Resolved value.

Example:

from pydash import result

obj = {'a': {'b': lambda: 'hello'}}
result(obj, 'a.b')  # 'hello' (function is called)

obj2 = {'a': {'b': 'world'}}
result(obj2, 'a.b')  # 'world' (value is returned)

retry

def retry(func: Callable, times: int = 1, delay: int = 0, **kwargs: Any) -> Any

Retry function execution with specified number of attempts.

Parameters:

  • func (Callable): Function to retry.
  • times (int): Number of retry attempts. Defaults to 1.
  • delay (int): Delay between retries in milliseconds. Defaults to 0.
  • kwargs (**Any): Additional keyword arguments.

Returns:

  • Any: Function result or raises last exception.

Example:

from pydash import retry
import random

def flaky_function():
    if random.random() < 0.7:
        raise Exception("Random failure")
    return "Success!"

# Retry up to 3 times with 100ms delay
result = retry(flaky_function, times=3, delay=100)

properties

def properties(obj: Any) -> List[str]

Creates a list of the own and inherited enumerable property names of object.

Parameters:

  • obj (Any): Object to inspect.

Returns:

  • List[str]: List of property names.

Example:

from pydash import properties

class MyClass:
    def __init__(self):
        self.prop1 = 'value1'
        self.prop2 = 'value2'

obj = MyClass()
properties(obj)  # ['prop1', 'prop2'] (plus inherited properties)

Usage Examples

Configuration and Defaults

from pydash import default_to, default_to_any, constant

def create_config(user_config=None):
    config = {
        'timeout': default_to(user_config.get('timeout') if user_config else None, 5000),
        'retries': default_to(user_config.get('retries') if user_config else None, 3),
        'debug': default_to(user_config.get('debug') if user_config else None, False)
    }
    return config

# Using constants for default callbacks
DEFAULT_SUCCESS = constant('Operation completed')
DEFAULT_ERROR = constant('Operation failed')

def api_call(endpoint, success_callback=DEFAULT_SUCCESS, error_callback=DEFAULT_ERROR):
    # ... API logic
    pass

Property Access and Manipulation

from pydash import property_, property_of, matches_property, map_

# Extract specific fields from data
users = [
    {'id': 1, 'name': 'John', 'profile': {'email': 'john@example.com'}},
    {'id': 2, 'name': 'Jane', 'profile': {'email': 'jane@example.com'}}
]

# Create property accessors
get_name = property_('name')
get_email = property_('profile.email')

names = map_(users, get_name)  # ['John', 'Jane']  
emails = map_(users, get_email)  # ['john@example.com', 'jane@example.com']

# Filter by property value
is_john = matches_property('name', 'John')
john_user = filter_(users, is_john)

Conditional Logic and Validation

from pydash import cond, conforms, over_every, over_some

# Complex conditional logic
process_number = cond([
    [lambda x: x < 0, lambda x: f"Negative: {abs(x)}"],
    [lambda x: x == 0, constant("Zero")],
    [lambda x: x % 2 == 0, lambda x: f"Even: {x}"],
    [lambda x: True, lambda x: f"Odd: {x}"]  # Default case
])

# Data validation
user_validator = conforms({
    'email': lambda x: '@' in x and '.' in x,
    'age': lambda x: isinstance(x, int) and 0 < x < 150,
    'name': lambda x: isinstance(x, str) and len(x.strip()) > 0
})

# Complex predicates
is_valid_number = over_every(
    lambda x: isinstance(x, (int, float)),
    lambda x: not math.isnan(x) if isinstance(x, float) else True,
    lambda x: x >= 0
)

Memoization and Performance

from pydash import memoize, times

# Expensive computation with caching
@memoize
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

# Custom cache key resolver
@memoize(resolver=lambda args, kwargs: f"{args[0]}:{kwargs.get('precision', 2)}")
def expensive_calculation(value, precision=2):
    # Simulate expensive operation
    return round(value ** 0.5, precision)

# Generate test data
test_cases = times(10, lambda i: random.random() * 100)

Utility Factories and Helpers

from pydash import method, method_of, nth_arg, unique_id

# Create method invokers
uppercase = method('upper')
split_lines = method('split', '\n')

# Process strings
texts = ['hello world', 'foo\nbar\nbaz']
upper_texts = map_(texts, uppercase)  # ['HELLO WORLD', 'FOO\nBAR\nBAZ']

# Argument selectors for function composition
get_first = nth_arg(0)
get_second = nth_arg(1)
get_last = nth_arg(-1)

# ID generation for resources
generate_user_id = lambda: unique_id('user_')
generate_session_id = lambda: unique_id('session_')

user_id = generate_user_id()  # 'user_1'
session_id = generate_session_id()  # 'session_2'

This Utilities module provides comprehensive helper functionality with 38 functions covering function creation, value generation, conditional logic, property access, and various utility patterns essential for functional programming and general application development.

Install with Tessl CLI

npx tessl i tessl/pypi-pydash

docs

arrays.md

chaining.md

collections.md

functions.md

index.md

numerical.md

objects.md

predicates.md

strings.md

utilities.md

tile.json