A comprehensive Python utility library for functional programming inspired by JavaScript's Lo-Dash
—
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.
def constant(value: Any) -> CallableCreates 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.14159def identity(value: Any) -> AnyReturns 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]def iteratee(func: Any = None) -> CallableCreates 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}) # Truedef matches(source: Any) -> CallableCreates 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'}]def matches_property(path: Union[str, List], src_value: Any) -> CallableCreates 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)def method(path: Union[str, List], *args: Any, **kwargs: Any) -> CallableCreates 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']def method_of(obj: Any, *args: Any, **kwargs: Any) -> CallableCreates 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'def noop(*args: Any, **kwargs: Any) -> NoneA 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 resultdef property_(path: Union[str, List]) -> CallableCreates 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'def property_of(obj: Any) -> CallableCreates 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'def now() -> intReturns 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., 1634567890123def 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.8234def 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]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]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']def unique_id(prefix: str = '') -> strGenerates 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'def stub_dict() -> DictReturns a new empty dictionary.
Parameters: None
Returns:
Dict: Empty dictionary.Example:
from pydash import stub_dict
stub_dict() # {}def stub_false() -> boolReturns False.
Parameters: None
Returns:
bool: False.Example:
from pydash import stub_false
stub_false() # Falsedef stub_list() -> ListReturns a new empty list.
Parameters: None
Returns:
List: Empty list.Example:
from pydash import stub_list
stub_list() # []def stub_string() -> strReturns an empty string.
Parameters: None
Returns:
str: Empty string.Example:
from pydash import stub_string
stub_string() # ''def stub_true() -> boolReturns True.
Parameters: None
Returns:
bool: True.Example:
from pydash import stub_true
stub_true() # Truedef attempt(func: Callable, *args: Any, **kwargs: Any) -> AnyAttempts 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) # Truedef default_to(value: Any, default_value: Any) -> AnyChecks 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) # 10def default_to_any(value: Any, *default_values: Any) -> AnyLike 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) # 2def 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']def cond(pairs: List[Tuple[Callable, Callable]]) -> CallableCreates 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'def conforms(source: Dict[str, Callable]) -> CallableCreates 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}]def conforms_to(obj: Any, source: Dict[str, Callable]) -> boolChecks 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) # Truedef over_every(*predicates: Callable) -> CallableCreates 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) # Falsedef over_some(*predicates: Callable) -> CallableCreates 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([]) # Falsedef over(*iteratees: Callable) -> CallableCreates 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]def memoize(func: Callable, resolver: Callable = None) -> CallableCreates 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)def nth_arg(n: int = 0) -> CallableCreates 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'def result(obj: Any, path: Union[str, List], default: Any = None) -> AnyResolves 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)def retry(func: Callable, times: int = 1, delay: int = 0, **kwargs: Any) -> AnyRetry 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)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)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
passfrom 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)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
)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)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