pyutils package

Submodules

pyutils.array module

Array utility functions.

This module provides utility functions for working with arrays/lists, ported from the jsutils library.

pyutils.array.range_list(start, end=None, step=1)[source]

Generate a list of integers from start to end (exclusive).

Parameters:
  • start (int) – Starting value (or end if end is None)

  • end (int | None) – Ending value (exclusive), optional

  • step (int) – Step size, defaults to 1

Return type:

list[int]

Returns:

List of integers

Examples

>>> range_list(5)
[0, 1, 2, 3, 4]
>>> range_list(2, 5)
[2, 3, 4]
>>> range_list(0, 10, 2)
[0, 2, 4, 6, 8]
pyutils.array.range_iter(start, end=None, step=1)[source]

Generate integers from start to end (exclusive).

Parameters:
  • start (int) – Starting value (or end if end is None)

  • end (int | None) – Ending value (exclusive), optional

  • step (int) – Step size, defaults to 1

Yields:

Integer values

Return type:

Generator[int, None, None]

Examples

>>> list(range_iter(3))
[0, 1, 2]
>>> list(range_iter(1, 4))
[1, 2, 3]
pyutils.array.boil(items, reducer_fn, initial_value=None)[source]

Reduce a list to a single value using a reducer function.

Parameters:
  • items (list[TypeVar(T)]) – List of items to reduce

  • reducer_fn (Callable[[TypeVar(T), TypeVar(T)], TypeVar(T)]) – Function that takes accumulator and current item, returns new accumulator

  • initial_value (Optional[TypeVar(T)]) – Initial value for the accumulator

Return type:

Optional[TypeVar(T)]

Returns:

The final reduced value, or initial_value if list is empty

Examples

>>> boil([1, 2, 3, 4], lambda acc, x: acc + x, 0)
10
>>> boil([1, 2, 3, 4], lambda acc, x: acc * x, 1)
24
>>> boil(['a', 'b', 'c'], lambda acc, x: acc + x, '')
'abc'
pyutils.array.chunk(items, size)[source]

Split a list into chunks of specified size.

Parameters:
  • items (list[TypeVar(T)]) – List to split

  • size (int) – Size of each chunk

Return type:

list[list[TypeVar(T)]]

Returns:

List of chunks

Raises:

ValueError – If size is less than or equal to 0

Examples

>>> chunk([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]
>>> chunk(['a', 'b', 'c', 'd'], 3)
[['a', 'b', 'c'], ['d']]
pyutils.array.count_by(items, key_fn)[source]

Count items by a key function.

Parameters:
  • items (list[TypeVar(T)]) – List of items to count

  • key_fn (Callable[[TypeVar(T)], TypeVar(K)]) – Function to extract key from each item

Return type:

dict[TypeVar(K), int]

Returns:

Dictionary mapping keys to counts

Examples

>>> count_by(['apple', 'banana', 'apricot'], lambda x: x[0])
{'a': 2, 'b': 1}
>>> count_by([1, 2, 3, 4, 5], lambda x: x % 2)
{1: 3, 0: 2}
pyutils.array.diff(old_list, new_list)[source]

Find items that are in old_list but not in new_list.

Parameters:
  • old_list (list[TypeVar(T)]) – Original list

  • new_list (list[TypeVar(T)]) – New list

Return type:

list[TypeVar(T)]

Returns:

List of items that were removed (in old_list but not in new_list)

Examples

>>> diff([1, 2, 3, 4], [2, 4])
[1, 3]
>>> diff([1, 2, 3], [1, 2, 3])
[]
>>> diff([1, 1, 2, 3], [1])
[2, 3]
pyutils.array.first(items, default=None)[source]

Get the first item from a list.

Parameters:
  • items (list[TypeVar(T)]) – List to get first item from

  • default (Optional[TypeVar(T)]) – Default value if list is empty

Return type:

Optional[TypeVar(T)]

Returns:

First item or default value

Examples

>>> first([1, 2, 3])
1
>>> first([], 'default')
'default'
pyutils.array.last(items, default=None)[source]

Get the last item from a list.

Parameters:
  • items (list[TypeVar(T)]) – List to get last item from

  • default (Optional[TypeVar(T)]) – Default value if list is empty

Return type:

Optional[TypeVar(T)]

Returns:

Last item or default value

Examples

>>> last([1, 2, 3])
3
>>> last([], 'default')
'default'
pyutils.array.fork(items, condition)[source]

Split a list into two based on a condition.

Parameters:
  • items (list[TypeVar(T)]) – List to split

  • condition (Callable[[TypeVar(T)], bool]) – Function to test each item

Return type:

tuple[list[TypeVar(T)], list[TypeVar(T)]]

Returns:

Tuple of (items_matching_condition, items_not_matching_condition)

Examples

>>> fork([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
([2, 4], [1, 3, 5])
>>> fork(['apple', 'banana', 'cherry'], lambda x: len(x) > 5)
(['banana', 'cherry'], ['apple'])
pyutils.array.has_intersects(list1, list2)[source]

Check if two lists have any common elements.

Parameters:
  • list1 (list[TypeVar(T)]) – First list

  • list2 (list[TypeVar(T)]) – Second list

Return type:

bool

Returns:

True if lists have common elements, False otherwise

Examples

>>> has_intersects([1, 2, 3], [3, 4, 5])
True
>>> has_intersects([1, 2], [3, 4])
False
pyutils.array.max_by(items, key_fn)[source]

Find the item with the maximum value according to a key function.

Parameters:
  • items (list[TypeVar(T)]) – List of items

  • key_fn (Callable[[TypeVar(T)], Any]) – Function to extract comparison value

Return type:

Optional[TypeVar(T)]

Returns:

Item with maximum value, or None if list is empty

Examples

>>> max_by(['apple', 'banana', 'cherry'], len)
'banana'
>>> max_by([{'age': 20}, {'age': 30}, {'age': 25}], lambda x: x['age'])
{'age': 30}
pyutils.array.min_by(items, key_fn)[source]

Find the item with the minimum value according to a key function.

Parameters:
  • items (list[TypeVar(T)]) – List of items

  • key_fn (Callable[[TypeVar(T)], Any]) – Function to extract comparison value

Return type:

Optional[TypeVar(T)]

Returns:

Item with minimum value, or None if list is empty

Examples

>>> min_by(['apple', 'banana', 'cherry'], len)
'apple'
>>> min_by([{'age': 20}, {'age': 30}, {'age': 25}], lambda x: x['age'])
{'age': 20}
pyutils.array.toggle(items, item)[source]

Add item to list if not present, remove if present.

Parameters:
  • items (list[TypeVar(T)]) – List to toggle item in

  • item (TypeVar(T)) – Item to toggle

Return type:

list[TypeVar(T)]

Returns:

New list with item toggled

Examples

>>> toggle([1, 2, 3], 4)
[1, 2, 3, 4]
>>> toggle([1, 2, 3], 2)
[1, 3]
pyutils.array.sum_by(items, key_fn)[source]

Sum values extracted from items using a key function.

Parameters:
  • items (list[TypeVar(T)]) – List of items

  • key_fn (Callable[[TypeVar(T)], int | float]) – Function to extract numeric value from each item

Return type:

int | float

Returns:

Sum of extracted values

Examples

>>> sum_by([{'value': 10}, {'value': 20}, {'value': 30}], lambda x: x['value'])
60
>>> sum_by(['hello', 'world', 'python'], len)
16
pyutils.array.zip_object(keys, values)[source]

Create a dictionary from lists of keys and values.

Parameters:
  • keys (list[TypeVar(K)]) – List of keys

  • values (list[TypeVar(V)]) – List of values

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

Dictionary mapping keys to values

Examples

>>> zip_object(['a', 'b', 'c'], [1, 2, 3])
{'a': 1, 'b': 2, 'c': 3}
>>> zip_object(['name', 'age'], ['Alice', 25])
{'name': 'Alice', 'age': 25}
pyutils.array.zip_lists(*lists)[source]

Zip multiple lists together.

Parameters:

*lists (list[TypeVar(T)]) – Variable number of lists to zip

Return type:

list[tuple[TypeVar(T), ...]]

Returns:

List of tuples containing corresponding elements

Examples

>>> zip_lists([1, 2, 3], ['a', 'b', 'c'])
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> zip_lists([1, 2], [3, 4], [5, 6])
[(1, 3, 5), (2, 4, 6)]
pyutils.array.unique(items)[source]

Remove duplicate items from a list while preserving order.

Parameters:

items (list[TypeVar(T)]) – List with potential duplicates

Return type:

list[TypeVar(T)]

Returns:

List with duplicates removed

Examples

>>> unique([1, 2, 2, 3, 1, 4])
[1, 2, 3, 4]
>>> unique(['a', 'b', 'a', 'c', 'b'])
['a', 'b', 'c']
pyutils.array.shuffle(items)[source]

Return a new list with items in random order.

Parameters:

items (list[TypeVar(T)]) – List to shuffle

Return type:

list[TypeVar(T)]

Returns:

New shuffled list

Examples

>>> original = [1, 2, 3, 4, 5]
>>> shuffled = shuffle(original)
>>> len(shuffled) == len(original)
True
>>> set(shuffled) == set(original)
True
pyutils.array.alphabetical(items, key_fn=None)[source]

Sort strings alphabetically (case-insensitive by default).

Parameters:
  • items (list[str]) – List of strings to sort

  • key_fn (Callable[[str], str] | None) – Optional function to extract sort key from each string

Return type:

list[str]

Returns:

New sorted list

Examples

>>> alphabetical(['banana', 'apple', 'cherry'])
['apple', 'banana', 'cherry']
>>> alphabetical(['Banana', 'apple', 'Cherry'])
['apple', 'Banana', 'Cherry']
pyutils.array.filter_list(items, predicate)[source]

Filter a list based on a predicate function.

Parameters:
  • items (list[TypeVar(T)]) – List to filter

  • predicate (Callable[[TypeVar(T)], bool]) – Function that returns True for items to keep

Return type:

list[TypeVar(T)]

Returns:

New list containing only items that match the predicate

Examples

>>> filter_list([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
[2, 4]
>>> filter_list(['apple', 'banana', 'cherry'], lambda x: len(x) > 5)
['banana', 'cherry']
>>> filter_list(
...     ['DB_HOST=localhost', 'DB_PORT=5432', 'API_KEY=secret'],
...     lambda x: x.startswith('DB_')
... )
['DB_HOST=localhost', 'DB_PORT=5432']

pyutils.async_utils module

Async utility functions.

This module provides utility functions for working with asynchronous operations, including sleep, timeout, and concurrent execution utilities, ported from the jsutils library.

async pyutils.async_utils.sleep_async(seconds)[source]

Asynchronously sleep for the specified number of seconds.

Parameters:

seconds (float) – Number of seconds to sleep

Return type:

None

Examples

>>> import asyncio
>>> async def main():
...     await sleep_async(0.1)
...     print("Slept for 0.1 seconds")
>>> # asyncio.run(main())
async pyutils.async_utils.timeout(coro, timeout_seconds, default=None)[source]

Execute coroutine with timeout.

Parameters:
  • coro (Awaitable[TypeVar(T)]) – Coroutine to execute

  • timeout_seconds (float) – Timeout in seconds

  • default (Optional[TypeVar(T)]) – Default value to return on timeout

Return type:

TypeVar(T)

Returns:

Result of coroutine or default value

Raises:

asyncio.TimeoutError – If timeout occurs and no default provided

Examples

>>> async def slow_operation():
...     await asyncio.sleep(2)
...     return "done"
>>>
>>> async def main():
...     result = await timeout(slow_operation(), 1.0, "timeout")
...     print(result)  # "timeout"
>>> # asyncio.run(main())
async pyutils.async_utils.delay(value, seconds)[source]

Return a value after a delay.

Parameters:
  • value (TypeVar(T)) – Value to return after delay

  • seconds (float) – Delay in seconds

Return type:

TypeVar(T)

Returns:

The provided value after delay

Examples

>>> async def main():
...     result = await delay("hello", 0.1)
...     print(result)  # "hello" (after 0.1 seconds)
>>> # asyncio.run(main())
async pyutils.async_utils.gather_with_concurrency(*coroutines, limit=10)[source]

Execute coroutines with concurrency limit.

Parameters:
  • *coroutines (Awaitable[TypeVar(T)]) – Coroutines to execute

  • limit (int) – Maximum number of concurrent executions

Return type:

list[TypeVar(T)]

Returns:

List of results in order

Examples

>>> async def fetch_data(i):
...     await asyncio.sleep(0.1)
...     return f"data_{i}"
>>>
>>> async def main():
...     tasks = [fetch_data(i) for i in range(5)]
...     results = await gather_with_concurrency(*tasks, limit=2)
...     print(results)  # ['data_0', 'data_1', 'data_2', 'data_3', 'data_4']
>>> # asyncio.run(main())
async pyutils.async_utils.race(*coroutines)[source]

Return the result of the first coroutine to complete.

Parameters:

*coroutines (Awaitable[TypeVar(T)]) – Coroutines to race

Return type:

TypeVar(T)

Returns:

Result of the first completed coroutine

Examples

>>> async def slow():
...     await asyncio.sleep(1)
...     return "slow"
>>>
>>> async def fast():
...     await asyncio.sleep(0.1)
...     return "fast"
>>>
>>> async def main():
...     result = await race(slow(), fast())
...     print(result)  # "fast"
>>> # asyncio.run(main())
async pyutils.async_utils.retry_async(coro_func, max_retries=3, delay=0, backoff_factor=1, should_retry=None)[source]

Retry an async function with exponential backoff.

Parameters:
  • coro_func (Callable[[], Awaitable[TypeVar(T)]]) – Function that returns a coroutine

  • max_retries (int) – Maximum number of retry attempts

  • delay (float) – Initial delay between retries in seconds

  • backoff_factor (float) – Multiplier for delay on each retry

  • should_retry (Callable[[Exception], bool] | None) – Function to determine if error should trigger retry

Return type:

TypeVar(T)

Returns:

Result of successful execution

Raises:

Exception – Last exception if all retries failed

Examples

>>> async def unreliable_api():
...     import random
...     if random.random() < 0.7:
...         raise Exception("API Error")
...     return "success"
>>>
>>> async def main():
...     result = await retry_async(
...         unreliable_api,
...         max_retries=3,
...         delay=0.1,
...         backoff_factor=2
...     )
...     print(result)
>>> # asyncio.run(main())
async pyutils.async_utils.map_async(func, items, concurrency=10)[source]

Apply async function to list of items with concurrency control.

Parameters:
  • func (Callable[[TypeVar(T)], Awaitable[Any]]) – Async function to apply

  • items (list[TypeVar(T)]) – List of items to process

  • concurrency (int) – Maximum concurrent executions

Return type:

list[Any]

Returns:

List of results in order

Examples

>>> async def process_item(item):
...     await asyncio.sleep(0.1)
...     return item * 2
>>>
>>> async def main():
...     items = [1, 2, 3, 4, 5]
...     results = await map_async(process_item, items, concurrency=2)
...     print(results)  # [2, 4, 6, 8, 10]
>>> # asyncio.run(main())
async pyutils.async_utils.filter_async(predicate, items, concurrency=10)[source]

Filter list using async predicate with concurrency control.

Parameters:
  • predicate (Callable[[TypeVar(T)], Awaitable[bool]]) – Async predicate function

  • items (list[TypeVar(T)]) – List of items to filter

  • concurrency (int) – Maximum concurrent executions

Return type:

list[TypeVar(T)]

Returns:

Filtered list of items

Examples

>>> async def is_even_async(n):
...     await asyncio.sleep(0.01)
...     return n % 2 == 0
>>>
>>> async def main():
...     numbers = [1, 2, 3, 4, 5, 6]
...     evens = await filter_async(is_even_async, numbers)
...     print(evens)  # [2, 4, 6]
>>> # asyncio.run(main())
pyutils.async_utils.run_in_thread(func, *args, **kwargs)[source]

Run a synchronous function in a thread pool.

Parameters:
  • func (Callable[..., TypeVar(T)]) – Synchronous function to run

  • *args (Any) – Positional arguments

  • **kwargs (Any) – Keyword arguments

Return type:

Awaitable[TypeVar(T)]

Returns:

Awaitable result

Examples

>>> def cpu_intensive_task(n):
...     return sum(i * i for i in range(n))
>>>
>>> async def main():
...     result = await run_in_thread(cpu_intensive_task, 1000)
...     print(result)
>>> # asyncio.run(main())
async pyutils.async_utils.batch_process(items, processor, batch_size=100, concurrency=5)[source]

Process items in batches with concurrency control.

Parameters:
  • items (list[TypeVar(T)]) – Items to process

  • processor (Callable[[list[TypeVar(T)]], Awaitable[list[Any]]]) – Function to process a batch of items

  • batch_size (int) – Size of each batch

  • concurrency (int) – Maximum concurrent batch processing

Return type:

list[Any]

Returns:

Flattened list of all results

Examples

>>> async def process_batch(batch):
...     await asyncio.sleep(0.1)
...     return [item * 2 for item in batch]
>>>
>>> async def main():
...     items = list(range(10))
...     results = await batch_process(
...         items, process_batch, batch_size=3, concurrency=2
...     )
...     print(results)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> # asyncio.run(main())
class pyutils.async_utils.AsyncContextManager[source]

Bases: object

Base class for async context managers.

async __aenter__()[source]

Enter async context.

Return type:

AsyncContextManager

async __aexit__(exc_type, exc_val, exc_tb)[source]

Exit async context.

Return type:

None

class pyutils.async_utils.AsyncTimer[source]

Bases: AsyncContextManager

Async context manager for timing operations.

__init__()[source]

Initialize timer.

async __aenter__()[source]

Start timing.

Return type:

AsyncTimer

async __aexit__(exc_type, exc_val, exc_tb)[source]

Stop timing.

Return type:

None

async pyutils.async_utils.with_timeout_default(coro, timeout_seconds, default)[source]

Execute coroutine with timeout, returning default on timeout.

Parameters:
  • coro (Awaitable[TypeVar(T)]) – Coroutine to execute

  • timeout_seconds (float) – Timeout in seconds

  • default (TypeVar(T)) – Default value to return on timeout

Return type:

TypeVar(T)

Returns:

Result of coroutine or default value

Examples

>>> async def slow_task():
...     await asyncio.sleep(2)
...     return "completed"
>>>
>>> async def main():
...     result = await with_timeout_default(
...         slow_task(), 1.0, "timed_out"
...     )
...     print(result)  # "timed_out"
>>> # asyncio.run(main())
async pyutils.async_utils.wait_for_all(*coroutines, timeout=None)[source]

Wait for all coroutines to complete.

Parameters:
  • *coroutines (Awaitable[Any]) – Coroutines to wait for

  • timeout (float | None) – Optional timeout in seconds

Return type:

list[Any]

Returns:

List of results

Raises:

asyncio.TimeoutError – If timeout occurs

Examples

>>> async def task1():
...     await asyncio.sleep(0.1)
...     return "task1"
>>>
>>> async def task2():
...     await asyncio.sleep(0.2)
...     return "task2"
>>>
>>> async def main():
...     results = await wait_for_all(task1(), task2())
...     print(results)  # ["task1", "task2"]
>>> # asyncio.run(main())
async pyutils.async_utils.wait_for_any(*coroutines, timeout=None)[source]

Wait for any coroutine to complete.

Parameters:
  • *coroutines (Awaitable[TypeVar(T)]) – Coroutines to wait for

  • timeout (float | None) – Optional timeout in seconds

Return type:

TypeVar(T)

Returns:

Result of first completed coroutine

Raises:

asyncio.TimeoutError – If timeout occurs

Examples

>>> async def slow_task():
...     await asyncio.sleep(1)
...     return "slow"
>>>
>>> async def fast_task():
...     await asyncio.sleep(0.1)
...     return "fast"
>>>
>>> async def main():
...     result = await wait_for_any(slow_task(), fast_task())
...     print(result)  # "fast"
>>> # asyncio.run(main())

pyutils.bytes module

Bytes utility functions.

This module provides utility functions for working with bytes and byte strings, including parsing and formatting byte values with units, ported from the jsutils library.

class pyutils.bytes.Bytes[source]

Bases: object

Utility class for working with byte values and formatting.

UNITS: ClassVar[dict[str, int]] = {'b': 1, 'byte': 1, 'bytes': 1, 'gb': 1073741824, 'gigabyte': 1073741824, 'gigabytes': 1073741824, 'kb': 1024, 'kilobyte': 1024, 'kilobytes': 1024, 'mb': 1048576, 'megabyte': 1048576, 'megabytes': 1048576, 'pb': 1125899906842624, 'petabyte': 1125899906842624, 'petabytes': 1125899906842624, 'tb': 1099511627776, 'terabyte': 1099511627776, 'terabytes': 1099511627776}
UNIT_ABBR: ClassVar[list[str]] = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
classmethod convert(value)[source]

Convert between byte values and formatted strings.

Parameters:

value (str | int | float) – Either a byte count (int/float) or a byte string (str)

Return type:

int | str

Returns:

If input is numeric, returns formatted string If input is string, returns byte count as int

Examples

>>> Bytes.convert(1024)
'1 KB'
>>> Bytes.convert('1 KB')
1024
>>> Bytes.convert(1536)
'1.5 KB'
classmethod parse(byte_string)[source]

Parse a byte string into a numeric value.

Parameters:

byte_string (str) – String representation of bytes (e.g., ‘1 KB’, ‘500 MB’)

Return type:

int

Returns:

Number of bytes as integer

Raises:

ValueError – If the string format is invalid

Examples

>>> Bytes.parse('1 KB')
1024
>>> Bytes.parse('1.5 MB')
1572864
>>> Bytes.parse('500')
500
classmethod format(byte_count, decimals=1, thousand_separator=False)[source]

Format a byte count into a human-readable string.

Parameters:
  • byte_count (int | float) – Number of bytes

  • decimals (int) – Number of decimal places to show

  • thousand_separator (bool) – Whether to use thousand separators

Return type:

str

Returns:

Formatted byte string

Examples

>>> Bytes.format(1024)
'1 KB'
>>> Bytes.format(1536, decimals=2)
'1.50 KB'
>>> Bytes.format(1234567, thousand_separator=True)
'1.2 MB'
classmethod to_kb(byte_count)[source]

Convert bytes to kilobytes.

Parameters:

byte_count (int | float) – Number of bytes

Return type:

float

Returns:

Number of kilobytes

Examples

>>> Bytes.to_kb(1024)
1.0
>>> Bytes.to_kb(1536)
1.5
classmethod to_mb(byte_count)[source]

Convert bytes to megabytes.

Parameters:

byte_count (int | float) – Number of bytes

Return type:

float

Returns:

Number of megabytes

Examples

>>> Bytes.to_mb(1048576)
1.0
>>> Bytes.to_mb(1572864)
1.5
classmethod to_gb(byte_count)[source]

Convert bytes to gigabytes.

Parameters:

byte_count (int | float) – Number of bytes

Return type:

float

Returns:

Number of gigabytes

Examples

>>> Bytes.to_gb(1073741824)
1.0
>>> Bytes.to_gb(1610612736)
1.5
classmethod to_tb(byte_count)[source]

Convert bytes to terabytes.

Parameters:

byte_count (int | float) – Number of bytes

Return type:

float

Returns:

Number of terabytes

Examples

>>> Bytes.to_tb(1099511627776)
1.0
classmethod from_kb(kb_count)[source]

Convert kilobytes to bytes.

Parameters:

kb_count (int | float) – Number of kilobytes

Return type:

int

Returns:

Number of bytes

Examples

>>> Bytes.from_kb(1)
1024
>>> Bytes.from_kb(1.5)
1536
classmethod from_mb(mb_count)[source]

Convert megabytes to bytes.

Parameters:

mb_count (int | float) – Number of megabytes

Return type:

int

Returns:

Number of bytes

Examples

>>> Bytes.from_mb(1)
1048576
>>> Bytes.from_mb(1.5)
1572864
classmethod from_gb(gb_count)[source]

Convert gigabytes to bytes.

Parameters:

gb_count (int | float) – Number of gigabytes

Return type:

int

Returns:

Number of bytes

Examples

>>> Bytes.from_gb(1)
1073741824
>>> Bytes.from_gb(1.5)
1610612736
classmethod from_tb(tb_count)[source]

Convert terabytes to bytes.

Parameters:

tb_count (int | float) – Number of terabytes

Return type:

int

Returns:

Number of bytes

Examples

>>> Bytes.from_tb(1)
1099511627776
classmethod compare(value1, value2)[source]

Compare two byte values.

Parameters:
  • value1 (str | int | float) – First value (string or numeric)

  • value2 (str | int | float) – Second value (string or numeric)

Return type:

int

Returns:

-1 if value1 < value2, 0 if equal, 1 if value1 > value2

Examples

>>> Bytes.compare('1 KB', 1024)
0
>>> Bytes.compare('1 MB', '1 KB')
1
>>> Bytes.compare(512, '1 KB')
-1
pyutils.bytes.bytes_util(value)[source]

Convenience function for byte conversion.

Parameters:

value (str | int | float) – Either a byte count (int/float) or a byte string (str)

Return type:

int | str

Returns:

If input is numeric, returns formatted string If input is string, returns byte count as int

Examples

>>> bytes_util(1024)
'1 KB'
>>> bytes_util('1 KB')
1024
>>> bytes_util(1536)
'1.5 KB'
pyutils.bytes.humanize_bytes(byte_count, decimals=1, binary=True)[source]

Convert bytes to human readable format.

Parameters:
  • byte_count (int | float) – Number of bytes

  • decimals (int) – Number of decimal places

  • binary (bool) – Use binary (1024) or decimal (1000) units

Return type:

str

Returns:

Human readable byte string

Examples

>>> humanize_bytes(1024)
'1 KB'
>>> humanize_bytes(1000, binary=False)
'1 KB'
>>> humanize_bytes(1536, decimals=2)
'1.50 KB'
pyutils.bytes.parse_bytes(byte_string, binary=True)[source]

Parse byte string to integer.

Parameters:
  • byte_string (str) – String representation of bytes

  • binary (bool) – Use binary (1024) or decimal (1000) units

Return type:

int

Returns:

Number of bytes

Examples

>>> parse_bytes('1 KB')
1024
>>> parse_bytes('1 KB', binary=False)
1000
pyutils.bytes.get_hash(data, algorithm='md5')[source]

Generate hash for given data.

Parameters:
  • data (str) – String data to hash

  • algorithm (str) – Hash algorithm to use (‘md5’, ‘sha1’, ‘sha256’), defaults to ‘md5’

Return type:

str

Returns:

Hexadecimal hash string

Examples

>>> get_hash('hello')
'5d41402abc4b2a76b9719d911017c592'
>>> get_hash('hello', 'sha256')
'2cf24dba4f21d4288094e9b9eb4e5f0164e031c02c90b3a8b26f6c8b'
pyutils.bytes.to_base64(data)[source]

Encode string data to base64.

Parameters:

data (str) – String data to encode

Return type:

str

Returns:

Base64 encoded string

Examples

>>> to_base64('hello')
'aGVsbG8='
>>> to_base64('world')
'd29ybGQ='
pyutils.bytes.from_base64(data)[source]

Decode base64 string data.

Parameters:

data (str) – Base64 encoded string

Return type:

str

Returns:

Decoded string

Examples

>>> from_base64('aGVsbG8=')
'hello'
>>> from_base64('d29ybGQ=')
'world'

pyutils.cli module

Console script for pyutils.

pyutils.cli.main()[source]

Console script for pyutils.

Return type:

None

pyutils.collection module

Collection utility functions.

This module provides utility functions for working with collections, inspired by JavaScript array and object methods that are commonly used but not directly available in Python.

pyutils.collection.flat_map(items, mapper)[source]

Map each element and flatten the result.

Similar to JavaScript’s Array.prototype.flatMap().

Parameters:
  • items (list[TypeVar(T)]) – List of items to map and flatten

  • mapper (Callable[[TypeVar(T)], list[Any]]) – Function that maps each item to a list

Return type:

list[Any]

Returns:

Flattened list of mapped results

Examples

>>> flat_map([1, 2, 3], lambda x: [x, x * 2])
[1, 2, 2, 4, 3, 6]
>>> flat_map(['hello', 'world'], lambda x: list(x))
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
pyutils.collection.includes(items, search_item, from_index=0)[source]

Check if an array includes a certain value.

Similar to JavaScript’s Array.prototype.includes().

Parameters:
  • items (list[TypeVar(T)]) – List to search in

  • search_item (TypeVar(T)) – Item to search for

  • from_index (int) – Index to start searching from

Return type:

bool

Returns:

True if item is found, False otherwise

Examples

>>> includes([1, 2, 3], 2)
True
>>> includes([1, 2, 3], 4)
False
>>> includes([1, 2, 3, 2], 2, 2)
True
pyutils.collection.find_index(items, predicate, from_index=0)[source]

Find the index of the first element that satisfies the predicate.

Similar to JavaScript’s Array.prototype.findIndex().

Parameters:
  • items (list[TypeVar(T)]) – List to search in

  • predicate (Callable[[TypeVar(T)], bool]) – Function to test each element

  • from_index (int) – Index to start searching from

Return type:

int

Returns:

Index of first matching element, or -1 if not found

Examples

>>> find_index([1, 2, 3, 4], lambda x: x > 2)
2
>>> find_index([1, 2, 3, 4], lambda x: x > 10)
-1
pyutils.collection.find_last_index(items, predicate)[source]

Find the index of the last element that satisfies the predicate.

Similar to JavaScript’s Array.prototype.findLastIndex().

Parameters:
  • items (list[TypeVar(T)]) – List to search in

  • predicate (Callable[[TypeVar(T)], bool]) – Function to test each element

Return type:

int

Returns:

Index of last matching element, or -1 if not found

Examples

>>> find_last_index([1, 2, 3, 2, 4], lambda x: x == 2)
3
>>> find_last_index([1, 2, 3, 4], lambda x: x > 10)
-1
pyutils.collection.some(items, predicate)[source]

Test whether at least one element passes the test.

Similar to JavaScript’s Array.prototype.some().

Parameters:
  • items (list[TypeVar(T)]) – List to test

  • predicate (Callable[[TypeVar(T)], bool]) – Function to test each element

Return type:

bool

Returns:

True if at least one element passes the test

Examples

>>> some([1, 2, 3, 4], lambda x: x > 3)
True
>>> some([1, 2, 3, 4], lambda x: x > 10)
False
pyutils.collection.every(items, predicate)[source]

Test whether all elements pass the test.

Similar to JavaScript’s Array.prototype.every().

Parameters:
  • items (list[TypeVar(T)]) – List to test

  • predicate (Callable[[TypeVar(T)], bool]) – Function to test each element

Return type:

bool

Returns:

True if all elements pass the test

Examples

>>> every([2, 4, 6, 8], lambda x: x % 2 == 0)
True
>>> every([1, 2, 3, 4], lambda x: x % 2 == 0)
False
pyutils.collection.at(items, index)[source]

Get element at the given index, supporting negative indices.

Similar to JavaScript’s Array.prototype.at().

Parameters:
  • items (list[TypeVar(T)]) – List to access

  • index (int) – Index to access (can be negative)

Return type:

Optional[TypeVar(T)]

Returns:

Element at the index, or None if index is out of bounds

Examples

>>> at([1, 2, 3, 4], 1)
2
>>> at([1, 2, 3, 4], -1)
4
>>> at([1, 2, 3, 4], 10)
pyutils.collection.fill(items, value, start=0, end=None)[source]

Fill array elements with a static value.

Similar to JavaScript’s Array.prototype.fill().

Parameters:
  • items (list[TypeVar(T)]) – List to fill (modified in place)

  • value (Any) – Value to fill with

  • start (int) – Start index

  • end (int | None) – End index (exclusive)

Return type:

list[TypeVar(T)]

Returns:

The modified list

Examples

>>> fill([1, 2, 3, 4], 0)
[0, 0, 0, 0]
>>> fill([1, 2, 3, 4], 0, 1, 3)
[1, 0, 0, 4]
pyutils.collection.copy_within(items, target, start=0, end=None)[source]

Copy array elements within the array to another position.

Similar to JavaScript’s Array.prototype.copyWithin().

Parameters:
  • items (list[TypeVar(T)]) – List to modify (modified in place)

  • target (int) – Index to copy elements to

  • start (int) – Index to start copying from

  • end (int | None) – Index to stop copying from (exclusive)

Return type:

list[TypeVar(T)]

Returns:

The modified list

Examples

>>> copy_within([1, 2, 3, 4, 5], 0, 3)
[4, 5, 3, 4, 5]
>>> copy_within([1, 2, 3, 4, 5], 2, 0, 2)
[1, 2, 1, 2, 5]
pyutils.collection.group_by(items, key_fn)[source]

Group array elements by a key function.

Similar to JavaScript’s Object.groupBy() (proposed).

Parameters:
  • items (list[TypeVar(T)]) – List of items to group

  • key_fn (Callable[[TypeVar(T)], TypeVar(K)]) – Function to extract grouping key

Return type:

dict[TypeVar(K), list[TypeVar(T)]]

Returns:

Dictionary mapping keys to lists of items

Examples

>>> group_by(['apple', 'banana', 'apricot'], lambda x: x[0])
{'a': ['apple', 'apricot'], 'b': ['banana']}
>>> group_by([1, 2, 3, 4, 5], lambda x: x % 2)
{1: [1, 3, 5], 0: [2, 4]}
pyutils.collection.to_reversed(items)[source]

Return a new array with elements in reversed order.

Similar to JavaScript’s Array.prototype.toReversed().

Parameters:

items (list[TypeVar(T)]) – List to reverse

Return type:

list[TypeVar(T)]

Returns:

New list with elements in reversed order

Examples

>>> to_reversed([1, 2, 3, 4])
[4, 3, 2, 1]
>>> original = [1, 2, 3]
>>> reversed_list = to_reversed(original)
>>> original
[1, 2, 3]
pyutils.collection.to_sorted(items, key=None, reverse=False)[source]

Return a new sorted array.

Similar to JavaScript’s Array.prototype.toSorted().

Parameters:
  • items (list[TypeVar(T)]) – List to sort

  • key (Callable[[TypeVar(T)], Any] | None) – Function to extract comparison key

  • reverse (bool) – Whether to sort in reverse order

Return type:

list[TypeVar(T)]

Returns:

New sorted list

Examples

>>> to_sorted([3, 1, 4, 1, 5])
[1, 1, 3, 4, 5]
>>> to_sorted(['banana', 'apple', 'cherry'], key=len)
['apple', 'banana', 'cherry']
pyutils.collection.with_item(items, index, value)[source]

Return a new array with one element changed.

Similar to JavaScript’s Array.prototype.with().

Parameters:
  • items (list[TypeVar(T)]) – Original list

  • index (int) – Index to change

  • value (TypeVar(T)) – New value

Return type:

list[TypeVar(T)]

Returns:

New list with the element changed

Examples

>>> with_item([1, 2, 3, 4], 1, 'two')
[1, 'two', 3, 4]
>>> original = [1, 2, 3]
>>> modified = with_item(original, 0, 'one')
>>> original
[1, 2, 3]
pyutils.collection.entries(items)[source]

Return array of [index, value] pairs.

Similar to JavaScript’s Array.prototype.entries().

Parameters:

items (list[TypeVar(T)]) – List to get entries from

Return type:

list[tuple[int, TypeVar(T)]]

Returns:

List of (index, value) tuples

Examples

>>> entries(['a', 'b', 'c'])
[(0, 'a'), (1, 'b'), (2, 'c')]
pyutils.collection.keys(items)[source]

Return array of indices.

Similar to JavaScript’s Array.prototype.keys().

Parameters:

items (list[TypeVar(T)]) – List to get keys from

Return type:

list[int]

Returns:

List of indices

Examples

>>> keys(['a', 'b', 'c'])
[0, 1, 2]
pyutils.collection.values(items)[source]

Return array of values (copy of the array).

Similar to JavaScript’s Array.prototype.values().

Parameters:

items (list[TypeVar(T)]) – List to get values from

Return type:

list[TypeVar(T)]

Returns:

Copy of the list

Examples

>>> values(['a', 'b', 'c'])
['a', 'b', 'c']
pyutils.collection.splice(items, start, delete_count=0, *insert_items)[source]

Change array contents by removing/replacing existing elements.

Also supports adding new elements.

Similar to JavaScript’s Array.prototype.splice().

Parameters:
  • items (list[TypeVar(T)]) – List to modify (modified in place)

  • start (int) – Index to start changing the array

  • delete_count (int) – Number of elements to remove

  • *insert_items (TypeVar(T)) – Items to insert

Return type:

list[TypeVar(T)]

Returns:

List of removed elements

Examples

>>> arr = [1, 2, 3, 4, 5]
>>> removed = splice(arr, 2, 1, 'a', 'b')
>>> arr
[1, 2, 'a', 'b', 4, 5]
>>> removed
[3]

pyutils.date module

Date and time utility functions.

This module provides utility functions for working with dates and times, porting JavaScript Date object methods and other date utilities to Python.

pyutils.date.now()[source]

Get current timestamp in milliseconds.

Similar to JavaScript Date.now().

Return type:

int

Returns:

Current timestamp in milliseconds

Examples

>>> timestamp = now()
>>> isinstance(timestamp, int)
True
>>> timestamp > 0
True
pyutils.date.parse_date(date_string)[source]

Parse a date string into a datetime object (like JavaScript Date.parse()).

Parameters:

date_string (str) – Date string to parse

Return type:

datetime

Returns:

Parsed datetime object

Raises:

ValueError – If date string cannot be parsed

Examples

>>> parse_date('2023-01-01')
datetime.datetime(2023, 1, 1, 0, 0)
>>> parse_date('2023-01-01T12:30:45')
datetime.datetime(2023, 1, 1, 12, 30, 45)
pyutils.date.to_iso_string(dt)[source]

Convert datetime to ISO string (like JavaScript Date.toISOString()).

Parameters:

dt (datetime) – Datetime object to convert

Return type:

str

Returns:

ISO format string

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 30, 45)
>>> to_iso_string(dt)
'2023-01-01T12:30:45'
pyutils.date.to_date_string(dt)[source]

Convert datetime to date string (like JavaScript Date.toDateString()).

Parameters:

dt (datetime) – Datetime object to convert

Return type:

str

Returns:

Date string in format ‘YYYY-MM-DD’

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 30, 45)
>>> to_date_string(dt)
'2023-01-01'
pyutils.date.to_time_string(dt)[source]

Convert datetime to time string (like JavaScript Date.toTimeString()).

Parameters:

dt (datetime) – Datetime object to convert

Returns:

MM:SS’

Return type:

Time string in format ‘HH

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 30, 45)
>>> to_time_string(dt)
'12:30:45'
pyutils.date.get_time(dt)[source]

Get timestamp in milliseconds from datetime (like JavaScript Date.getTime()).

Parameters:

dt (datetime) – Datetime object

Return type:

int

Returns:

Timestamp in milliseconds

Examples

>>> dt = datetime.datetime(2023, 1, 1, 0, 0, 0)
>>> timestamp = get_time(dt)
>>> isinstance(timestamp, int)
True
pyutils.date.add_days(dt, days)[source]

Add days to a datetime object.

Parameters:
  • dt (datetime) – Base datetime

  • days (int) – Number of days to add (can be negative)

Return type:

datetime

Returns:

New datetime with days added

Examples

>>> dt = datetime.datetime(2023, 1, 1)
>>> add_days(dt, 5)
datetime.datetime(2023, 1, 6, 0, 0)
>>> add_days(dt, -1)
datetime.datetime(2022, 12, 31, 0, 0)
pyutils.date.add_hours(dt, hours)[source]

Add hours to a datetime object.

Parameters:
  • dt (datetime) – Base datetime

  • hours (int) – Number of hours to add (can be negative)

Return type:

datetime

Returns:

New datetime with hours added

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 0, 0)
>>> add_hours(dt, 3)
datetime.datetime(2023, 1, 1, 15, 0)
>>> add_hours(dt, -2)
datetime.datetime(2023, 1, 1, 10, 0)
pyutils.date.add_minutes(dt, minutes)[source]

Add minutes to a datetime object.

Parameters:
  • dt (datetime) – Base datetime

  • minutes (int) – Number of minutes to add (can be negative)

Return type:

datetime

Returns:

New datetime with minutes added

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 30, 0)
>>> add_minutes(dt, 15)
datetime.datetime(2023, 1, 1, 12, 45)
>>> add_minutes(dt, -10)
datetime.datetime(2023, 1, 1, 12, 20)
pyutils.date.format_relative_time(dt, base_dt=None)[source]

Format datetime as relative time string (like ‘X minutes ago’).

Parameters:
  • dt (datetime) – Datetime to format

  • base_dt (datetime | None) – Base datetime to compare against (defaults to now)

Return type:

str

Returns:

Relative time string

Examples

>>> import datetime
>>> now = datetime.datetime.now()
>>> past = now - datetime.timedelta(minutes=5)
>>> format_relative_time(past, now)
'5 minutes ago'
pyutils.date.is_valid_date(date_string)[source]

Check if a string represents a valid date.

Parameters:

date_string (str) – String to check

Return type:

bool

Returns:

True if valid date, False otherwise

Examples

>>> is_valid_date('2023-01-01')
True
>>> is_valid_date('invalid-date')
False
>>> is_valid_date('2023-13-01')  # Invalid month
False

pyutils.encoding module

Encoding and decoding utility functions.

This module provides utility functions for encoding and decoding, porting JavaScript encoding methods and other encoding utilities to Python.

pyutils.encoding.btoa(data)[source]

Encode string to base64 (like JavaScript btoa).

Parameters:

data (str) – String to encode

Return type:

str

Returns:

Base64 encoded string

Examples

>>> btoa('hello')
'aGVsbG8='
>>> btoa('Hello, World!')
'SGVsbG8sIFdvcmxkIQ=='
pyutils.encoding.atob(data)[source]

Decode base64 string (like JavaScript atob).

Parameters:

data (str) – Base64 string to decode

Return type:

str

Returns:

Decoded string

Raises:

ValueError – If input is not valid base64

Examples

>>> atob('aGVsbG8=')
'hello'
>>> atob('SGVsbG8sIFdvcmxkIQ==')
'Hello, World!'
pyutils.encoding.escape_html(text)[source]

Escape HTML special characters.

Parameters:

text (str) – Text to escape

Return type:

str

Returns:

HTML escaped text

Examples

>>> escape_html('<div>Hello & goodbye</div>')
'&lt;div&gt;Hello &amp; goodbye&lt;/div&gt;'
>>> escape_html('"quoted" text')
'&quot;quoted&quot; text'
pyutils.encoding.unescape_html(text)[source]

Unescape HTML entities.

Parameters:

text (str) – HTML text to unescape

Return type:

str

Returns:

Unescaped text

Examples

>>> unescape_html('&lt;div&gt;Hello &amp; goodbye&lt;/div&gt;')
'<div>Hello & goodbye</div>'
>>> unescape_html('&quot;quoted&quot; text')
'"quoted" text'
pyutils.encoding.encode_base64(data)[source]

Encode data to base64.

Parameters:

data (str | bytes) – Data to encode (string or bytes)

Return type:

str

Returns:

Base64 encoded string

Examples

>>> encode_base64('hello world')
'aGVsbG8gd29ybGQ='
>>> encode_base64(b'hello world')
'aGVsbG8gd29ybGQ='
pyutils.encoding.decode_base64(data)[source]

Decode base64 string to string.

Parameters:

data (str) – Base64 string to decode

Return type:

str

Returns:

Decoded string

Raises:

ValueError – If input is not valid base64

Examples

>>> decode_base64('aGVsbG8gd29ybGQ=')
'hello world'
pyutils.encoding.encode_hex(data)[source]

Encode data to hexadecimal.

Parameters:

data (str | bytes) – Data to encode (string or bytes)

Return type:

str

Returns:

Hexadecimal encoded string

Examples

>>> encode_hex('hello')
'68656c6c6f'
>>> encode_hex(b'hello')
'68656c6c6f'
pyutils.encoding.decode_hex(data)[source]

Decode hexadecimal string to string.

Parameters:

data (str) – Hexadecimal string to decode

Return type:

str

Returns:

Decoded string

Raises:

ValueError – If input is not valid hexadecimal

Examples

>>> decode_hex('68656c6c6f')
'hello'
pyutils.encoding.json_stringify(obj, indent=None)[source]

Convert object to JSON string (like JavaScript JSON.stringify).

Parameters:
  • obj (Any) – Object to convert

  • indent (int | None) – Indentation for pretty printing

Return type:

str

Returns:

JSON string

Examples

>>> json_stringify({'name': 'John', 'age': 30})
'{"name": "John", "age": 30}'
>>> json_stringify([1, 2, 3])
'[1, 2, 3]'
pyutils.encoding.json_parse(text)[source]

Parse JSON string to object (like JavaScript JSON.parse).

Parameters:

text (str) – JSON string to parse

Return type:

Any

Returns:

Parsed object

Raises:

ValueError – If input is not valid JSON

Examples

>>> json_parse('{"name": "John", "age": 30}')
{'name': 'John', 'age': 30}
>>> json_parse('[1, 2, 3]')
[1, 2, 3]
pyutils.encoding.url_encode(text)[source]

URL encode a string (like JavaScript encodeURIComponent).

Parameters:

text (str) – String to encode

Return type:

str

Returns:

URL encoded string

Examples

>>> url_encode('hello world')
'hello%20world'
>>> url_encode('user@example.com')
'user%40example.com'
pyutils.encoding.url_decode(text)[source]

URL decode a string (like JavaScript decodeURIComponent).

Parameters:

text (str) – String to decode

Return type:

str

Returns:

URL decoded string

Examples

>>> url_decode('hello%20world')
'hello world'
>>> url_decode('user%40example.com')
'user@example.com'
pyutils.encoding.escape_regex(text)[source]

Escape special regex characters in a string.

Parameters:

text (str) – String to escape

Return type:

str

Returns:

Escaped string safe for use in regex

Examples

>>> escape_regex('hello.world')
'hello\\.world'
>>> escape_regex('$100 (USD)')
'\\$100 \\(USD\\)'
pyutils.encoding.hash_string(text, algorithm='sha256')[source]

Generate hash of a string.

Parameters:
  • text (str) – String to hash

  • algorithm (str) – Hash algorithm (‘md5’, ‘sha1’, ‘sha256’, ‘sha512’)

Return type:

str

Returns:

Hexadecimal hash string

Raises:

ValueError – If algorithm is not supported

Examples

>>> len(hash_string('hello', 'md5'))
32
>>> len(hash_string('hello', 'sha256'))
64
pyutils.encoding.generate_random_string(length=16, charset='alphanumeric')[source]

Generate a random string.

Parameters:
  • length (int) – Length of the string to generate

  • charset (str) – Character set to use (‘alphanumeric’, ‘alpha’, ‘numeric’, ‘hex’) or custom string

Return type:

str

Returns:

Random string

Examples

>>> len(generate_random_string(10))
10
>>> all(c.isalnum() for c in generate_random_string(10, 'alphanumeric'))
True
pyutils.encoding.is_base64(text)[source]

Check if a string is valid base64.

Parameters:

text (str) – String to check

Return type:

bool

Returns:

True if valid base64, False otherwise

Examples

>>> is_base64('aGVsbG8=')
True
>>> is_base64('hello')
False
pyutils.encoding.is_hex(text)[source]

Check if a string is valid hexadecimal.

Note

This function does not accept hex strings with ‘0x’ or ‘0X’ prefixes. Use int(text, 16) if you need to handle prefixed hex strings.

Parameters:

text (str) – String to check

Return type:

bool

Returns:

True if valid hexadecimal, False otherwise

Examples

>>> is_hex('68656c6c6f')
True
>>> is_hex('hello')
False
>>> is_hex('123abc')
True
>>> is_hex('0x123')  # Prefixed hex strings are rejected
False
pyutils.encoding.is_json(text)[source]

Check if a string is valid JSON.

Parameters:

text (str) – String to check

Return type:

bool

Returns:

True if valid JSON, False otherwise

Examples

>>> is_json('{"name": "John"}')
True
>>> is_json('[1, 2, 3]')
True
>>> is_json('hello')
False

pyutils.function module

Function utility functions.

This module provides utility functions for working with functions, including debounce, throttle, retry mechanisms, and polling, ported from the jsutils library.

class pyutils.function.Debouncer(func, wait=0.2, leading=False, trailing=True)[source]

Bases: object

Debounce function calls.

A debounced function will only execute after it hasn’t been called for a specified wait time.

__init__(func, wait=0.2, leading=False, trailing=True)[source]

Initialize debouncer.

Parameters:
  • func (Callable[..., Any]) – Function to debounce

  • wait (float) – Wait time in seconds, defaults to 0.2

  • leading (bool) – Execute on leading edge, defaults to False

  • trailing (bool) – Execute on trailing edge, defaults to True

__call__(*args, **kwargs)[source]

Call the debounced function.

Return type:

Any

cancel()[source]

Cancel pending function call.

Return type:

None

pending()[source]

Check if function call is pending.

Return type:

bool

flush()[source]

Immediately execute pending function call.

Return type:

Any

pyutils.function.debounce(wait=0.2, leading=False, trailing=True)[source]

Decorator to debounce function calls.

Parameters:
  • wait (float) – Wait time in seconds, defaults to 0.2

  • leading (bool) – Execute on leading edge, defaults to False

  • trailing (bool) – Execute on trailing edge, defaults to True

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], Debouncer]

Returns:

Debounced function

Examples

>>> @debounce(wait=0.1)
... def save_data(data):
...     print(f"Saving {data}")
>>>
>>> save_data("test1")
>>> save_data("test2")  # Only this will execute after 0.1s
class pyutils.function.Throttler(func, wait=0.2, leading=False, trailing=True)[source]

Bases: object

Throttle function calls.

A throttled function will execute at most once per specified time period.

__init__(func, wait=0.2, leading=False, trailing=True)[source]

Initialize throttler.

Parameters:
  • func (Callable[..., Any]) – Function to throttle

  • wait (float) – Wait time in seconds, defaults to 0.2

  • leading (bool) – Execute on leading edge, defaults to False

  • trailing (bool) – Execute on trailing edge, defaults to True

__call__(*args, **kwargs)[source]

Call the throttled function.

Return type:

Any

cancel()[source]

Cancel pending function call.

Return type:

None

flush()[source]

Immediately execute pending function call.

Return type:

Any

pyutils.function.throttle(wait=0.2, leading=False, trailing=True)[source]

Decorator to throttle function calls.

Parameters:
  • wait (float) – Wait time in seconds, defaults to 0.2

  • leading (bool) – Execute on leading edge, defaults to False

  • trailing (bool) – Execute on trailing edge, defaults to True

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], Throttler]

Returns:

Throttled function

Examples

>>> @throttle(wait=0.1)
... def api_call(data):
...     print(f"API call with {data}")
>>>
>>> api_call("test1")  # Executes immediately
>>> api_call("test2")  # Ignored (within throttle period)
class pyutils.function.PollingController(task, stop_condition=None, error_action=None, on_progress=None, quit_on_error=True, interval=5.0, max_retries=3, immediate=False, max_executions=inf)[source]

Bases: object

Controller for polling operations.

__init__(task, stop_condition=None, error_action=None, on_progress=None, quit_on_error=True, interval=5.0, max_retries=3, immediate=False, max_executions=inf)[source]

Initialize polling controller.

Parameters:
  • task (Callable[[], Awaitable[TypeVar(T)]]) – Async task to poll

  • stop_condition (Callable[[TypeVar(T)], bool] | None) – Function to determine when to stop polling

  • error_action (Callable[[Exception], None] | None) – Function to handle errors

  • on_progress (Callable[[TypeVar(T)], None] | None) – Function called on each successful execution

  • quit_on_error (bool) – Whether to quit on max retries reached

  • interval (float) – Polling interval in seconds

  • max_retries (int) – Maximum retry attempts

  • immediate (bool) – Whether to execute immediately

  • max_executions (int | float) – Maximum number of executions

async start()[source]

Start polling.

Return type:

None

stop()[source]

Stop polling.

Return type:

None

status()[source]

Get current status.

Return type:

dict[str, Any]

pyutils.function.create_polling(task, stop_condition=None, error_action=None, on_progress=None, quit_on_error=True, interval=5.0, max_retries=3, immediate=False, max_executions=inf)[source]

Create a polling controller.

Parameters:
  • task (Callable[[], Awaitable[TypeVar(T)]]) – Async task to poll

  • stop_condition (Callable[[TypeVar(T)], bool] | None) – Function to determine when to stop polling

  • error_action (Callable[[Exception], None] | None) – Function to handle errors

  • on_progress (Callable[[TypeVar(T)], None] | None) – Function called on each successful execution

  • quit_on_error (bool) – Whether to quit on max retries reached

  • interval (float) – Polling interval in seconds

  • max_retries (int) – Maximum retry attempts

  • immediate (bool) – Whether to execute immediately

  • max_executions (int | float) – Maximum number of executions

Return type:

PollingController

Returns:

Polling controller

Examples

>>> async def fetch_data():
...     # Simulate API call
...     return {'status': 'processing'}
>>>
>>> poller = create_polling(
...     task=fetch_data,
...     stop_condition=lambda data: data['status'] == 'done',
...     interval=2.0
... )
>>> # await poller.start()
pyutils.function.with_retry(max_retries=3, delay=0, should_retry=None)[source]

Decorator to add retry functionality to a function.

Parameters:
  • max_retries (int) – Maximum number of retry attempts

  • delay (float) – Delay between retries in seconds

  • should_retry (Callable[[Exception], bool] | None) – Function to determine if error should trigger retry

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

Returns:

Decorated function with retry capability

Examples

>>> @with_retry(max_retries=3, delay=0.1)
... def unreliable_function():
...     import random
...     if random.random() < 0.7:
...         raise Exception("Random failure")
...     return "Success"
>>>
>>> # result = unreliable_function()  # Will retry up to 3 times
pyutils.function.memoize(func)[source]

Decorator to memoize function results.

Parameters:

func (TypeVar(F, bound= Callable[..., Any])) – Function to memoize

Return type:

TypeVar(F, bound= Callable[..., Any])

Returns:

Memoized function

Examples

>>> @memoize
... def expensive_calculation(n):
...     print(f"Computing for {n}")
...     return n * n
>>>
>>> expensive_calculation(5)  # Prints "Computing for 5"
25
>>> expensive_calculation(5)  # Uses cached result, no print
25
pyutils.function.once(func)[source]

Decorator to ensure function is called only once.

Parameters:

func (TypeVar(F, bound= Callable[..., Any])) – Function to call once

Return type:

TypeVar(F, bound= Callable[..., Any])

Returns:

Function that can only be called once

Examples

>>> @once
... def initialize():
...     print("Initializing...")
...     return "initialized"
>>>
>>> initialize()  # Prints "Initializing..."
'initialized'
>>> initialize()  # Returns cached result, no print
'initialized'

pyutils.math module

Math utility functions.

This module provides utility functions for mathematical operations, ported from the jsutils library.

pyutils.math.get_random_int(min_val, max_val)[source]

Generate a random integer between min and max (inclusive).

Parameters:
  • min_val (int) – Minimum value (inclusive)

  • max_val (int) – Maximum value (inclusive)

Return type:

int

Returns:

Random integer between min_val and max_val

Raises:

ValueError – If min_val > max_val

Examples

>>> result = get_random_int(1, 10)
>>> 1 <= result <= 10
True
>>> get_random_int(5, 5)
5
pyutils.math.get_random_item_from_array(items)[source]

Get a random item from a list.

Parameters:

items (list[TypeVar(T)]) – List to select from

Return type:

TypeVar(T)

Returns:

Random item from the list

Raises:

IndexError – If the list is empty

Examples

>>> items = [1, 2, 3, 4, 5]
>>> result = get_random_item_from_array(items)
>>> result in items
True
>>> get_random_item_from_array(['apple'])
'apple'
pyutils.math.clamp(value, min_val, max_val)[source]

Clamp a value between min and max bounds.

Parameters:
  • value (int | float) – Value to clamp

  • min_val (int | float) – Minimum bound

  • max_val (int | float) – Maximum bound

Return type:

int | float

Returns:

Clamped value

Examples

>>> clamp(5, 1, 10)
5
>>> clamp(-5, 1, 10)
1
>>> clamp(15, 1, 10)
10
pyutils.math.lerp(start, end, t)[source]

Linear interpolation between two values.

Parameters:
  • start (int | float) – Starting value

  • end (int | float) – Ending value

  • t (float) – Interpolation factor (0.0 to 1.0)

Return type:

float

Returns:

Interpolated value

Examples

>>> lerp(0, 10, 0.5)
5.0
>>> lerp(10, 20, 0.25)
12.5
>>> lerp(5, 15, 0.0)
5.0
pyutils.math.normalize(value, min_val, max_val)[source]

Normalize a value to a 0-1 range based on min and max bounds.

Parameters:
  • value (int | float) – Value to normalize

  • min_val (int | float) – Minimum bound

  • max_val (int | float) – Maximum bound

Return type:

float

Returns:

Normalized value (0.0 to 1.0)

Raises:

ZeroDivisionError – If max_val equals min_val (zero range)

Examples

>>> normalize(5, 0, 10)
0.5
>>> normalize(25, 0, 100)
0.25
>>> normalize(0, 0, 10)
0.0
pyutils.math.degrees_to_radians(degrees)[source]

Convert degrees to radians.

Parameters:

degrees (int | float) – Angle in degrees

Return type:

float

Returns:

Angle in radians

Examples

>>> import math
>>> abs(degrees_to_radians(180) - math.pi) < 1e-10
True
>>> abs(degrees_to_radians(90) - math.pi/2) < 1e-10
True
pyutils.math.radians_to_degrees(radians)[source]

Convert radians to degrees.

Parameters:

radians (int | float) – Angle in radians

Return type:

float

Returns:

Angle in degrees

Examples

>>> import math
>>> abs(radians_to_degrees(math.pi) - 180) < 1e-10
True
>>> abs(radians_to_degrees(math.pi/2) - 90) < 1e-10
True
pyutils.math.is_even(number)[source]

Check if a number is even.

Parameters:

number (int) – Integer to check

Return type:

bool

Returns:

True if even, False if odd

Examples

>>> is_even(4)
True
>>> is_even(5)
False
>>> is_even(0)
True
pyutils.math.is_odd(number)[source]

Check if a number is odd.

Parameters:

number (int) – Integer to check

Return type:

bool

Returns:

True if odd, False if even

Examples

>>> is_odd(4)
False
>>> is_odd(5)
True
>>> is_odd(0)
False
pyutils.math.gcd(a, b)[source]

Calculate the greatest common divisor of two integers.

Parameters:
  • a (int) – First integer

  • b (int) – Second integer

Return type:

int

Returns:

Greatest common divisor

Examples

>>> gcd(12, 8)
4
>>> gcd(17, 13)
1
>>> gcd(0, 5)
5
pyutils.math.lcm(a, b)[source]

Calculate the least common multiple of two integers.

Parameters:
  • a (int) – First integer

  • b (int) – Second integer

Return type:

int

Returns:

Least common multiple

Examples

>>> lcm(12, 8)
24
>>> lcm(3, 5)
15
>>> lcm(0, 5)
0
pyutils.math.factorial(n)[source]

Calculate the factorial of a non-negative integer.

Parameters:

n (int) – Non-negative integer

Return type:

int

Returns:

Factorial of n

Raises:

ValueError – If n is negative

Examples

>>> factorial(5)
120
>>> factorial(0)
1
>>> factorial(1)
1
pyutils.math.is_prime(n)[source]

Check if a number is prime.

Parameters:

n (int) – Integer to check

Return type:

bool

Returns:

True if prime, False otherwise

Examples

>>> is_prime(7)
True
>>> is_prime(8)
False
>>> is_prime(2)
True
>>> is_prime(1)
False
pyutils.math.fibonacci(n)[source]

Calculate the nth Fibonacci number.

Parameters:

n (int) – Position in Fibonacci sequence (0-indexed)

Return type:

int

Returns:

nth Fibonacci number

Raises:

ValueError – If n is negative

Examples

>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(10)
55
pyutils.math.round_to_precision(value, precision)[source]

Round a number to specified decimal places.

Parameters:
  • value (float) – Number to round

  • precision (int) – Number of decimal places

Return type:

float

Returns:

Rounded number

Examples

>>> round_to_precision(3.14159, 2)
3.14
>>> round_to_precision(2.5, 0)
2.0

pyutils.object module

Object utility functions.

This module provides utility functions for working with dictionaries and objects, ported from the jsutils library.

pyutils.object.pick(obj, keys)[source]

Create a new dictionary with only the specified keys.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

  • keys (list[TypeVar(K)]) – List of keys to pick

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

New dictionary with only the specified keys

Examples

>>> pick({'a': 1, 'b': 2, 'c': 3}, ['a', 'c'])
{'a': 1, 'c': 3}
>>> pick({'name': 'Alice', 'age': 25, 'city': 'NYC'}, ['name', 'age'])
{'name': 'Alice', 'age': 25}
pyutils.object.pick_by(obj, predicate)[source]

Create a new dictionary with key-value pairs that satisfy the predicate.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

  • predicate (Callable[[TypeVar(V), TypeVar(K)], bool]) – Function that takes (value, key) and returns boolean

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

New dictionary with filtered key-value pairs

Examples

>>> pick_by({'a': 1, 'b': 2, 'c': 3}, lambda v, k: v > 1)
{'b': 2, 'c': 3}
>>> pick_by({'name': 'Alice', 'age': 25}, lambda v, k: isinstance(v, str))
{'name': 'Alice'}
pyutils.object.omit(obj, keys)[source]

Create a new dictionary without the specified keys.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

  • keys (list[TypeVar(K)]) – List of keys to omit

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

New dictionary without the specified keys

Examples

>>> omit({'a': 1, 'b': 2, 'c': 3}, ['b'])
{'a': 1, 'c': 3}
>>> omit({'name': 'Alice', 'age': 25, 'city': 'NYC'}, ['age', 'city'])
{'name': 'Alice'}
pyutils.object.omit_by(obj, predicate)[source]

Create a new dictionary without key-value pairs that satisfy the predicate.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

  • predicate (Callable[[TypeVar(V), TypeVar(K)], bool]) – Function that takes (value, key) and returns boolean

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

New dictionary with filtered key-value pairs

Examples

>>> omit_by({'a': 1, 'b': 2, 'c': 3}, lambda v, k: v > 1)
{'a': 1}
>>> omit_by({'name': 'Alice', 'age': 25}, lambda v, k: isinstance(v, int))
{'name': 'Alice'}
pyutils.object.map_keys(obj, mapper)[source]

Create a new dictionary with transformed keys.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

  • mapper (Callable[[TypeVar(K)], TypeVar(T)]) – Function to transform keys

Return type:

dict[TypeVar(T), TypeVar(V)]

Returns:

New dictionary with transformed keys

Examples

>>> map_keys({'a': 1, 'b': 2}, str.upper)
{'A': 1, 'B': 2}
>>> map_keys({1: 'one', 2: 'two'}, lambda x: f'num_{x}')
{'num_1': 'one', 'num_2': 'two'}
pyutils.object.map_values(obj, mapper)[source]

Create a new dictionary with transformed values.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

  • mapper (Callable[[TypeVar(V)], TypeVar(T)]) – Function to transform values

Return type:

dict[TypeVar(K), TypeVar(T)]

Returns:

New dictionary with transformed values

Examples

>>> map_values({'a': 1, 'b': 2}, lambda x: x * 2)
{'a': 2, 'b': 4}
>>> map_values({'name': 'alice', 'city': 'nyc'}, str.upper)
{'name': 'ALICE', 'city': 'NYC'}
pyutils.object.is_object(value)[source]

Check if a value is a dictionary (object-like).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a dictionary, False otherwise

Examples

>>> is_object({'a': 1})
True
>>> is_object([1, 2, 3])
False
>>> is_object('string')
False
>>> is_object(None)
False
pyutils.object.merge(*dicts)[source]

Recursively merge multiple dictionaries.

Parameters:

*dicts (dict[Any, Any]) – Dictionaries to merge

Return type:

dict[Any, Any]

Returns:

Merged dictionary

Examples

>>> merge({'a': 1}, {'b': 2})
{'a': 1, 'b': 2}
>>> merge({'a': {'x': 1}}, {'a': {'y': 2}})
{'a': {'x': 1, 'y': 2}}
>>> merge({'a': 1}, {'a': 2})
{'a': 2}
pyutils.object.remove_non_serializable_props(obj)[source]

Remove properties that cannot be JSON serialized.

Parameters:

obj (Any) – Object to clean

Return type:

Any

Returns:

Object with only JSON-serializable properties

Examples

>>> import datetime
>>> data = {'name': 'Alice', 'func': lambda x: x, 'date': 'today'}
>>> cleaned = remove_non_serializable_props(data)
>>> 'name' in cleaned
True
>>> 'func' in cleaned
False
pyutils.object.safe_json_stringify(obj, indent=None)[source]

Safely convert object to JSON string, removing non-serializable properties.

Parameters:
  • obj (Any) – Object to stringify

  • indent (int | None) – JSON indentation, optional

Return type:

str

Returns:

JSON string

Examples

>>> safe_json_stringify({'name': 'Alice', 'age': 25})
'{"name": "Alice", "age": 25}'
>>> import datetime
>>> data = {'name': 'Alice', 'func': lambda x: x}
>>> result = safe_json_stringify(data)
>>> 'name' in result
True
>>> 'func' in result
False
pyutils.object.invert(obj)[source]

Create a new dictionary with keys and values swapped.

Parameters:

obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

Return type:

dict[TypeVar(V), TypeVar(K)]

Returns:

New dictionary with keys and values swapped

Examples

>>> invert({'a': 1, 'b': 2})
{1: 'a', 2: 'b'}
>>> invert({'name': 'Alice', 'age': 25})
{'Alice': 'name', 25: 'age'}
pyutils.object.deep_copy(obj)[source]

Create a deep copy of an object.

Parameters:

obj (Any) – Object to copy

Return type:

Any

Returns:

Deep copy of the object

Examples

>>> original = {'a': {'b': 1}}
>>> copied = deep_copy(original)
>>> copied['a']['b'] = 2
>>> original['a']['b']
1
pyutils.object.flatten_dict(obj, separator='.', prefix='')[source]

Flatten a nested dictionary.

Parameters:
  • obj (dict[str, Any]) – Dictionary to flatten

  • separator (str) – Separator for nested keys, defaults to ‘.’

  • prefix (str) – Prefix for keys, defaults to ‘’

Return type:

dict[str, Any]

Returns:

Flattened dictionary

Examples

>>> flatten_dict({'a': {'b': {'c': 1}}})
{'a.b.c': 1}
>>> flatten_dict({'user': {'name': 'Alice', 'age': 25}})
{'user.name': 'Alice', 'user.age': 25}
pyutils.object.unflatten_dict(obj, separator='.')[source]

Unflatten a flattened dictionary.

Parameters:
  • obj (dict[str, Any]) – Flattened dictionary

  • separator (str) – Separator used in keys, defaults to ‘.’

Return type:

dict[str, Any]

Returns:

Nested dictionary

Examples

>>> unflatten_dict({'a.b.c': 1})
{'a': {'b': {'c': 1}}}
>>> unflatten_dict({'user.name': 'Alice', 'user.age': 25})
{'user': {'name': 'Alice', 'age': 25}}
pyutils.object.get_nested_value(obj, path, separator='.', default=None)[source]

Get a nested value from a dictionary using a path.

Parameters:
  • obj (dict[str, Any]) – Source dictionary

  • path (str) – Path to the value (e.g., ‘user.profile.name’)

  • separator (str) – Path separator, defaults to ‘.’

  • default (Any) – Default value if path not found

Return type:

Any

Returns:

Value at the specified path or default

Examples

>>> data = {'user': {'profile': {'name': 'Alice'}}}
>>> get_nested_value(data, 'user.profile.name')
'Alice'
>>> get_nested_value(data, 'user.profile.age', default=0)
0
pyutils.object.set_nested_value(obj, path, value, separator='.')[source]

Set a nested value in a dictionary using a path.

Parameters:
  • obj (dict[str, Any]) – Target dictionary (will be modified)

  • path (str) – Path to set the value (e.g., ‘user.profile.name’)

  • value (Any) – Value to set

  • separator (str) – Path separator, defaults to ‘.’

Return type:

dict[str, Any]

Returns:

The modified dictionary

Examples

>>> data = {}
>>> set_nested_value(data, 'user.profile.name', 'Alice')
{'user': {'profile': {'name': 'Alice'}}}
>>> data
{'user': {'profile': {'name': 'Alice'}}}
pyutils.object.get(obj, key, default=None)[source]

Get a value from a dictionary with optional default.

Parameters:
  • obj (dict[str, Any]) – Source dictionary

  • key (str) – Key to retrieve

  • default (Any) – Default value if key not found

Return type:

Any

Returns:

Value at the specified key or default

Examples

>>> get({'name': 'Alice', 'age': 25}, 'name')
'Alice'
>>> get({'name': 'Alice'}, 'age', 0)
0
>>> get({}, 'nonexistent') is None
True
pyutils.object.clone(obj)[source]

Create a shallow copy of an object.

Parameters:

obj (Any) – Object to clone

Return type:

Any

Returns:

Shallow copy of the object

Examples

>>> original = {'a': 1, 'b': [1, 2, 3]}
>>> cloned = clone(original)
>>> cloned['a'] = 2
>>> original['a']
1
>>> cloned['b'] is original['b']
True
pyutils.object.set_value(obj, key, value)[source]

Set a value in a dictionary.

Parameters:
  • obj (dict[str, Any]) – Target dictionary (will be modified)

  • key (str) – Key to set

  • value (Any) – Value to set

Return type:

dict[str, Any]

Returns:

The modified dictionary

Examples

>>> data = {'name': 'Alice'}
>>> set_value(data, 'age', 25)
{'name': 'Alice', 'age': 25}
>>> data
{'name': 'Alice', 'age': 25}
pyutils.object.has(obj, key)[source]

Check if a dictionary has a specific key.

Parameters:
  • obj (dict[str, Any]) – Dictionary to check

  • key (str) – Key to look for

Return type:

bool

Returns:

True if key exists, False otherwise

Examples

>>> has({'name': 'Alice', 'age': 25}, 'name')
True
>>> has({'name': 'Alice'}, 'age')
False
pyutils.object.filter_dict(obj, predicate)[source]

Filter a dictionary based on a predicate function.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Dictionary to filter

  • predicate (Callable[[TypeVar(K), TypeVar(V)], bool]) – Function that takes key and value, returns True to keep

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

New dictionary with filtered key-value pairs

Examples

>>> filter_dict({'a': 1, 'b': 2, 'c': 3}, lambda k, v: v > 1)
{'b': 2, 'c': 3}
>>> filter_dict({'DB_HOST': 'localhost', 'API_KEY': 'secret'},
...              lambda k, v: k.startswith('DB_'))
{'DB_HOST': 'localhost'}

pyutils.string module

String utility functions.

This module provides utility functions for working with strings, ported from the jsutils library.

pyutils.string.gen_all_cases_combination(text)[source]

Generate all common case combinations of a string.

Parameters:

text (str) – Input string

Return type:

dict[str, str]

Returns:

Dictionary with different case styles

Examples

>>> result = gen_all_cases_combination('hello_world')
>>> result['camelCase']
'helloWorld'
>>> result['PascalCase']
'HelloWorld'
pyutils.string.generate_uuid()[source]

Generate a UUID string.

Return type:

str

Returns:

UUID string

Examples

>>> uuid_str = generate_uuid()
>>> len(uuid_str)
36
>>> '-' in uuid_str
True
pyutils.string.generate_base62_code(length=8)[source]

Generate a random Base62 string.

Parameters:

length (int) – Length of the generated string, defaults to 8

Return type:

str

Returns:

Random Base62 string

Examples

>>> code = generate_base62_code(10)
>>> len(code)
10
>>> all(c in string_module.ascii_letters + string_module.digits for c in code)
True
pyutils.string.fuzzy_match(pattern, text)[source]

Calculate fuzzy match score between pattern and text.

Parameters:
  • pattern (str) – Pattern to match

  • text (str) – Text to search in

Return type:

float

Returns:

Similarity score between 0.0 and 1.0

Examples

>>> fuzzy_match('hello', 'hello')
1.0
>>> fuzzy_match('hello', 'world')
0.0
>>> fuzzy_match('hello', 'helo')
0.8
pyutils.string.get_file_ext(filename)[source]

Get file extension from filename.

Parameters:

filename (str) – Filename to extract extension from

Return type:

str

Returns:

File extension (without dot)

Examples

>>> get_file_ext('document.pdf')
'pdf'
>>> get_file_ext('archive.tar.gz')
'gz'
>>> get_file_ext('README')
''
>>> get_file_ext('.gitignore')
''
>>> get_file_ext('.config.json')
'json'
pyutils.string.capitalize(text)[source]

Capitalize the first letter of each word in a string.

Parameters:

text (str) – Input string

Return type:

str

Returns:

String with first letter of each word capitalized

Examples

>>> capitalize('hello world')
'Hello World'
>>> capitalize('HELLO')
'Hello'
>>> capitalize('   ')
'   '
pyutils.string.camel_case(text)[source]

Convert string to camelCase.

Parameters:

text (str) – Input string

Return type:

str

Returns:

camelCase string

Examples

>>> camel_case('hello world')
'helloWorld'
>>> camel_case('hello-world-test')
'helloWorldTest'
>>> camel_case('hello_world_test')
'helloWorldTest'
>>> camel_case('helloWorld')
'helloWorld'
pyutils.string.snake_case(text)[source]

Convert string to snake_case.

Parameters:

text (str) – Input string

Return type:

str

Returns:

snake_case string

Examples

>>> snake_case('Hello World')
'hello_world'
>>> snake_case('helloWorld')
'hello_world'
>>> snake_case('hello-world')
'hello_world'
pyutils.string.dash_case(text)[source]

Convert string to dash-case (kebab-case).

Parameters:

text (str) – Input string

Return type:

str

Returns:

dash-case string

Examples

>>> dash_case('Hello World')
'hello-world'
>>> dash_case('helloWorld')
'hello-world'
>>> dash_case('hello_world')
'hello-world'
pyutils.string.pascal_case(text)[source]

Convert string to PascalCase.

Parameters:

text (str) – Input string

Return type:

str

Returns:

PascalCase string

Examples

>>> pascal_case('hello world')
'HelloWorld'
>>> pascal_case('hello-world-test')
'HelloWorldTest'
>>> pascal_case('hello_world_test')
'HelloWorldTest'
>>> pascal_case('helloWorld')
'HelloWorld'
pyutils.string.parse_template(template, variables)[source]

Parse template string with variable substitution.

Parameters:
  • template (str) – Template string with {variable} placeholders

  • variables (dict[str, str | int | float]) – Dictionary of variable values

Return type:

str

Returns:

Parsed string with variables substituted

Examples

>>> parse_template('Hello {name}!', {'name': 'World'})
'Hello World!'
>>> parse_template('{greeting} {name}, you are {age} years old',
...                {'greeting': 'Hi', 'name': 'Alice', 'age': 25})
'Hi Alice, you are 25 years old'
pyutils.string.trim(text, chars=None)[source]

Remove specified characters from both ends of string.

Parameters:
  • text (str) – Input string

  • chars (str | None) – Characters to remove, defaults to whitespace

Return type:

str

Returns:

Trimmed string

Examples

>>> trim('  hello  ')
'hello'
>>> trim('...hello...', '.')
'hello'
>>> trim('abcHELLOcba', 'abc')
'HELLO'
pyutils.string.trim_start(text, chars=None)[source]

Remove specified characters from the start of string.

Parameters:
  • text (str) – Input string

  • chars (str | None) – Characters to remove, defaults to whitespace

Return type:

str

Returns:

Left-trimmed string

Examples

>>> trim_start('  hello  ')
'hello  '
>>> trim_start('...hello...', '.')
'hello...'
pyutils.string.trim_end(text, chars=None)[source]

Remove specified characters from the end of string.

Parameters:
  • text (str) – Input string

  • chars (str | None) – Characters to remove, defaults to whitespace

Return type:

str

Returns:

Right-trimmed string

Examples

>>> trim_end('  hello  ')
'  hello'
>>> trim_end('...hello...', '.')
'...hello'
pyutils.string.remove_prefix(text, prefix)[source]

Remove prefix from string if present.

Parameters:
  • text (str) – Input string

  • prefix (str) – Prefix to remove

Return type:

str

Returns:

String with prefix removed

Examples

>>> remove_prefix('hello world', 'hello ')
'world'
>>> remove_prefix('test string', 'hello')
'test string'
pyutils.string.remove_suffix(text, suffix)[source]

Remove suffix from string if present.

Parameters:
  • text (str) – Input string

  • suffix (str) – Suffix to remove

Return type:

str

Returns:

String with suffix removed

Examples

>>> remove_suffix('hello world', ' world')
'hello'
>>> remove_suffix('test string', 'hello')
'test string'
pyutils.string.generate_merge_paths(paths)[source]

Generate a merged path from a list of path segments.

Parameters:

paths (list[str]) – List of path segments

Return type:

str

Returns:

Merged path

Examples

>>> generate_merge_paths(['path1', 'path2', 'file.txt'])
'path1/path2/file.txt'
>>> generate_merge_paths(['C:', 'Users', 'Alice'])
'C:/Users/Alice'
pyutils.string.slugify(text, separator='-')[source]

Convert string to URL-friendly slug.

Parameters:
  • text (str) – Input string

  • separator (str) – Separator character, defaults to ‘-’

Return type:

str

Returns:

URL-friendly slug

Examples

>>> slugify('Hello World!')
'hello-world'
>>> slugify('This is a Test!', '_')
'this_is_a_test'
pyutils.string.truncate(text, length, suffix='...')[source]

Truncate string to specified length with optional suffix.

Parameters:
  • text (str) – Input string

  • length (int) – Maximum length

  • suffix (str) – Suffix to add if truncated, defaults to ‘…’

Return type:

str

Returns:

Truncated string

Examples

>>> truncate('Hello World', 5)
'Hello...'
>>> truncate('Hello World', 20)
'Hello World'
>>> truncate('Hello World', 8, '...')
'Hello...'
pyutils.string.word_count(text)[source]

Count words in a string.

Parameters:

text (str) – Input string

Return type:

int

Returns:

Number of words

Examples

>>> word_count('Hello world')
2
>>> word_count('  Hello   world  test  ')
3
>>> word_count('')
0
pyutils.string.reverse(text)[source]

Reverse a string.

Parameters:

text (str) – Input string

Return type:

str

Returns:

Reversed string

Examples

>>> reverse('hello')
'olleh'
>>> reverse('Python')
'nohtyP'

pyutils.type_utils module

Type utility functions.

This module provides utility functions for type checking and conversion, porting JavaScript type checking methods and other type utilities to Python.

pyutils.type_utils.is_array(value)[source]

Check if value is an array (list or tuple).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a list or tuple, False otherwise

Examples

>>> is_array([1, 2, 3])
True
>>> is_array((1, 2, 3))
True
>>> is_array('string')
False
pyutils.type_utils.is_string(value)[source]

Check if value is a string.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a string, False otherwise

Examples

>>> is_string('hello')
True
>>> is_string(123)
False
pyutils.type_utils.is_number(value)[source]

Check if value is a number (int or float).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a number, False otherwise

Examples

>>> is_number(123)
True
>>> is_number(3.14)
True
>>> is_number('123')
False
pyutils.type_utils.is_boolean(value)[source]

Check if value is a boolean.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a boolean, False otherwise

Examples

>>> is_boolean(True)
True
>>> is_boolean(False)
True
>>> is_boolean(1)
False
pyutils.type_utils.is_null(value)[source]

Check if value is None (null in JavaScript).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is None, False otherwise

Examples

>>> is_null(None)
True
>>> is_null(0)
False
>>> is_null('')
False
pyutils.type_utils.is_undefined(value)[source]

Check if value is undefined (similar to JavaScript undefined).

In Python context, this checks for None or missing attributes.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is None, False otherwise

Examples

>>> is_undefined(None)
True
>>> is_undefined(0)
False
pyutils.type_utils.is_function(value)[source]

Check if value is a function or callable.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is callable, False otherwise

Examples

>>> is_function(lambda x: x)
True
>>> is_function(print)
True
>>> is_function('string')
False
pyutils.type_utils.is_object(value)[source]

Check if value is an object (dict in Python).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a dict, False otherwise

Examples

>>> is_object({'key': 'value'})
True
>>> is_object([])
False
>>> is_object('string')
False
pyutils.type_utils.is_date(value)[source]

Check if value is a date/datetime object.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a date or datetime, False otherwise

Examples

>>> import datetime
>>> is_date(datetime.datetime.now())
True
>>> is_date(datetime.date.today())
True
>>> is_date('2023-01-01')
False
pyutils.type_utils.is_regex(value)[source]

Check if value is a compiled regular expression.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a compiled regex, False otherwise

Examples

>>> import re
>>> is_regex(re.compile(r'\d+'))
True
>>> is_regex(r'\d+')
False
pyutils.type_utils.is_empty(value)[source]

Check if value is empty (like JavaScript’s concept of empty).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is empty, False otherwise

Examples

>>> is_empty('')
True
>>> is_empty([])
True
>>> is_empty({})
True
>>> is_empty(set())
True
>>> is_empty(frozenset())
True
>>> is_empty(None)
True
>>> is_empty(0)
False
pyutils.type_utils.is_nan(value)[source]

Check if value is NaN (Not a Number).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is NaN, False otherwise

Examples

>>> is_nan(float('nan'))
True
>>> is_nan(123)
False
>>> is_nan('string')
False
pyutils.type_utils.is_finite(value)[source]

Check if value is a finite number.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a finite number, False otherwise

Examples

>>> is_finite(123)
True
>>> is_finite(3.14)
True
>>> is_finite(float('inf'))
False
>>> is_finite(float('nan'))
False
pyutils.type_utils.is_integer(value)[source]

Check if value is an integer (like JavaScript Number.isInteger).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is an integer, False otherwise

Examples

>>> is_integer(123)
True
>>> is_integer(3.0)
True
>>> is_integer(3.14)
False
>>> is_integer('123')
False
pyutils.type_utils.to_string(value)[source]

Convert value to string (like JavaScript String() constructor).

Parameters:

value (Any) – Value to convert

Return type:

str

Returns:

String representation of value

Examples

>>> to_string(123)
'123'
>>> to_string(True)
'True'
>>> to_string([1, 2, 3])
'[1, 2, 3]'
pyutils.type_utils.to_number(value)[source]

Convert value to number (like JavaScript Number() constructor).

Parameters:

value (Any) – Value to convert

Return type:

int | float

Returns:

Number representation of value, or NaN if conversion fails

Examples

>>> to_number('123')
123
>>> to_number('3.14')
3.14
>>> import math
>>> math.isnan(to_number('invalid'))
True
>>> to_number(True)
1
pyutils.type_utils.to_boolean(value)[source]

Convert value to boolean (like JavaScript Boolean() constructor).

Parameters:

value (Any) – Value to convert

Return type:

bool

Returns:

Boolean representation of value

Examples

>>> to_boolean(1)
True
>>> to_boolean(0)
False
>>> to_boolean('')
False
>>> to_boolean('hello')
True
>>> to_boolean([])
False
pyutils.type_utils.parse_int(value, radix=10)[source]

Parse string to integer (like JavaScript parseInt).

Parameters:
  • value (Any) – String to parse

  • radix (int) – Base for parsing (2-36), defaults to 10

Return type:

int | float

Returns:

Parsed integer or NaN if parsing fails

Examples

>>> parse_int('123')
123
>>> parse_int('123.45')
123
>>> parse_int('ff', 16)
255
>>> import math
>>> math.isnan(parse_int('invalid'))
True
pyutils.type_utils.parse_float(value)[source]

Parse string to float (like JavaScript parseFloat).

Parameters:

value (Any) – String to parse

Return type:

float

Returns:

Parsed float or NaN if parsing fails

Examples

>>> parse_float('3.14')
3.14
>>> parse_float('3.14abc')
3.14
>>> import math
>>> math.isnan(parse_float('abc'))
True
pyutils.type_utils.typeof(value)[source]

Get type of value (like JavaScript typeof operator).

Parameters:

value (Any) – Value to check type of

Return type:

str

Returns:

Type string

Examples

>>> typeof('hello')
'string'
>>> typeof(123)
'number'
>>> typeof(True)
'boolean'
>>> typeof(None)
'undefined'
>>> typeof({})
'object'
>>> typeof([])
'object'
>>> typeof(lambda x: x)
'function'

pyutils.url module

URL utility functions.

This module provides utility functions for working with URLs, porting JavaScript URL object methods and other URL utilities to Python.

class pyutils.url.URLParser(url, base=None)[source]

Bases: object

URL parser class similar to JavaScript URL object.

Provides methods to parse and manipulate URLs similar to the JavaScript URL API.

__init__(url, base=None)[source]

Initialize URL parser.

Parameters:
  • url (str) – URL string to parse

  • base (str | None) – Base URL for relative URLs

Examples

>>> parser = URLParser('https://example.com/path?query=value#hash')
>>> parser.hostname
'example.com'
property href: str

Get the complete URL.

Returns:

Complete URL string

property protocol: str

Get the protocol (scheme) of the URL.

Returns:

‘)

Return type:

Protocol string (e.g., ‘https

property hostname: str

Get the hostname of the URL.

Returns:

Hostname string

property port: str

Get the port of the URL.

Returns:

Port string (empty if default port)

property pathname: str

Get the pathname of the URL.

Returns:

Pathname string (defaults to ‘/’ if empty)

property search: str

Get the search (query) string of the URL.

Returns:

Search string including ‘?’ prefix

property hash: str

Get the hash (fragment) of the URL.

Returns:

Hash string including ‘#’ prefix

property origin: str

Get the origin of the URL.

Returns:

Origin string (protocol + hostname + port)

property username: str

Get the username from the URL.

Returns:

Username string

property password: str

Get the password from the URL.

Returns:

Password string

get_query_params()[source]

Get query parameters as a dictionary.

Return type:

dict[str, str]

Returns:

Dictionary of query parameters

Examples

>>> parser = URLParser('https://example.com?name=John&age=30')
>>> params = parser.get_query_params()
>>> params['name']
'John'
pyutils.url.parse_url(url, base=None)[source]

Parse a URL string into a dictionary.

Parameters:
  • url (str) – URL string to parse

  • base (str | None) – Base URL for relative URLs

Return type:

dict[str, str]

Returns:

Dictionary with URL components

Examples

>>> result = parse_url('https://example.com/path')
>>> result['hostname']
'example.com'
pyutils.url.encode_uri_component(text)[source]

Encode a string for use in a URI component (like JavaScript encodeURIComponent).

Parameters:

text (str) – String to encode

Return type:

str

Returns:

Encoded string

Examples

>>> encode_uri_component('hello world')
'hello%20world'
>>> encode_uri_component('user@example.com')
'user%40example.com'
pyutils.url.decode_uri_component(text)[source]

Decode a URI component string (like JavaScript decodeURIComponent).

Parameters:

text (str) – String to decode

Return type:

str

Returns:

Decoded string

Raises:

ValueError – If the string contains invalid percent encoding

Examples

>>> decode_uri_component('hello%20world')
'hello world'
>>> decode_uri_component('user%40example.com')
'user@example.com'
pyutils.url.encode_uri(uri)[source]

Encode a complete URI (like JavaScript encodeURI).

Parameters:

uri (str) – URI to encode

Return type:

str

Returns:

Encoded URI

Examples

>>> encode_uri('https://example.com/path with spaces')
'https://example.com/path%20with%20spaces'
pyutils.url.decode_uri(uri)[source]

Decode a complete URI (like JavaScript decodeURI).

Parameters:

uri (str) – URI to decode

Return type:

str

Returns:

Decoded URI

Examples

>>> decode_uri('https://example.com/path%20with%20spaces')
'https://example.com/path with spaces'
pyutils.url.build_url(protocol='http', hostname='', port=None, pathname='', query_params=None, hash_fragment='')[source]

Build a URL from components.

Parameters:
  • protocol (str) – Protocol (without colon)

  • hostname (str) – Hostname

  • port (int | None) – Port number

  • pathname (str) – Path

  • query_params (dict[str, str] | None) – Query parameters

  • hash_fragment (str) – Hash fragment

Return type:

str

Returns:

Complete URL string

Examples

>>> build_url(
...     hostname='example.com',
...     pathname='/api/users',
...     query_params={'page': '1'}
... )
'http://example.com/api/users?page=1'
pyutils.url.is_valid_url(url)[source]

Check if a string is a valid URL.

Parameters:

url (str) – String to check

Return type:

bool

Returns:

True if valid URL, False otherwise

Examples

>>> is_valid_url('https://example.com')
True
>>> is_valid_url('not-a-url')
False
>>> is_valid_url('ftp://files.example.com')
True
pyutils.url.get_domain(url)[source]

Extract domain from URL.

Parameters:

url (str) – URL string

Return type:

str | None

Returns:

Domain string or None if invalid

Examples

>>> get_domain('https://www.example.com/path')
'www.example.com'
>>> get_domain('http://subdomain.example.org:8080/api')
'subdomain.example.org'
>>> get_domain('invalid-url')
None
pyutils.url.get_query_params(url)[source]

Extract query parameters from URL.

Parameters:

url (str) – URL string

Return type:

dict[str, str]

Returns:

Dictionary of query parameters

Examples

>>> get_query_params(
...     'https://example.com/path?foo=bar&baz=qux'
... )
{'foo': 'bar', 'baz': 'qux'}
>>> get_query_params('https://example.com/path')
{}

Module contents

Top-level package for pyutils.

A comprehensive Python utility library providing functions for array manipulation, string processing, mathematical operations, object handling, function utilities, asynchronous operations, and byte processing.

Ported from the jsutils JavaScript library to provide similar functionality in Python.

class pyutils.Bytes[source]

Bases: object

Utility class for working with byte values and formatting.

UNITS: ClassVar[dict[str, int]] = {'b': 1, 'byte': 1, 'bytes': 1, 'gb': 1073741824, 'gigabyte': 1073741824, 'gigabytes': 1073741824, 'kb': 1024, 'kilobyte': 1024, 'kilobytes': 1024, 'mb': 1048576, 'megabyte': 1048576, 'megabytes': 1048576, 'pb': 1125899906842624, 'petabyte': 1125899906842624, 'petabytes': 1125899906842624, 'tb': 1099511627776, 'terabyte': 1099511627776, 'terabytes': 1099511627776}
UNIT_ABBR: ClassVar[list[str]] = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
classmethod compare(value1, value2)[source]

Compare two byte values.

Parameters:
  • value1 (str | int | float) – First value (string or numeric)

  • value2 (str | int | float) – Second value (string or numeric)

Return type:

int

Returns:

-1 if value1 < value2, 0 if equal, 1 if value1 > value2

Examples

>>> Bytes.compare('1 KB', 1024)
0
>>> Bytes.compare('1 MB', '1 KB')
1
>>> Bytes.compare(512, '1 KB')
-1
classmethod convert(value)[source]

Convert between byte values and formatted strings.

Parameters:

value (str | int | float) – Either a byte count (int/float) or a byte string (str)

Return type:

int | str

Returns:

If input is numeric, returns formatted string If input is string, returns byte count as int

Examples

>>> Bytes.convert(1024)
'1 KB'
>>> Bytes.convert('1 KB')
1024
>>> Bytes.convert(1536)
'1.5 KB'
classmethod format(byte_count, decimals=1, thousand_separator=False)[source]

Format a byte count into a human-readable string.

Parameters:
  • byte_count (int | float) – Number of bytes

  • decimals (int) – Number of decimal places to show

  • thousand_separator (bool) – Whether to use thousand separators

Return type:

str

Returns:

Formatted byte string

Examples

>>> Bytes.format(1024)
'1 KB'
>>> Bytes.format(1536, decimals=2)
'1.50 KB'
>>> Bytes.format(1234567, thousand_separator=True)
'1.2 MB'
classmethod from_gb(gb_count)[source]

Convert gigabytes to bytes.

Parameters:

gb_count (int | float) – Number of gigabytes

Return type:

int

Returns:

Number of bytes

Examples

>>> Bytes.from_gb(1)
1073741824
>>> Bytes.from_gb(1.5)
1610612736
classmethod from_kb(kb_count)[source]

Convert kilobytes to bytes.

Parameters:

kb_count (int | float) – Number of kilobytes

Return type:

int

Returns:

Number of bytes

Examples

>>> Bytes.from_kb(1)
1024
>>> Bytes.from_kb(1.5)
1536
classmethod from_mb(mb_count)[source]

Convert megabytes to bytes.

Parameters:

mb_count (int | float) – Number of megabytes

Return type:

int

Returns:

Number of bytes

Examples

>>> Bytes.from_mb(1)
1048576
>>> Bytes.from_mb(1.5)
1572864
classmethod from_tb(tb_count)[source]

Convert terabytes to bytes.

Parameters:

tb_count (int | float) – Number of terabytes

Return type:

int

Returns:

Number of bytes

Examples

>>> Bytes.from_tb(1)
1099511627776
classmethod parse(byte_string)[source]

Parse a byte string into a numeric value.

Parameters:

byte_string (str) – String representation of bytes (e.g., ‘1 KB’, ‘500 MB’)

Return type:

int

Returns:

Number of bytes as integer

Raises:

ValueError – If the string format is invalid

Examples

>>> Bytes.parse('1 KB')
1024
>>> Bytes.parse('1.5 MB')
1572864
>>> Bytes.parse('500')
500
classmethod to_gb(byte_count)[source]

Convert bytes to gigabytes.

Parameters:

byte_count (int | float) – Number of bytes

Return type:

float

Returns:

Number of gigabytes

Examples

>>> Bytes.to_gb(1073741824)
1.0
>>> Bytes.to_gb(1610612736)
1.5
classmethod to_kb(byte_count)[source]

Convert bytes to kilobytes.

Parameters:

byte_count (int | float) – Number of bytes

Return type:

float

Returns:

Number of kilobytes

Examples

>>> Bytes.to_kb(1024)
1.0
>>> Bytes.to_kb(1536)
1.5
classmethod to_mb(byte_count)[source]

Convert bytes to megabytes.

Parameters:

byte_count (int | float) – Number of bytes

Return type:

float

Returns:

Number of megabytes

Examples

>>> Bytes.to_mb(1048576)
1.0
>>> Bytes.to_mb(1572864)
1.5
classmethod to_tb(byte_count)[source]

Convert bytes to terabytes.

Parameters:

byte_count (int | float) – Number of bytes

Return type:

float

Returns:

Number of terabytes

Examples

>>> Bytes.to_tb(1099511627776)
1.0
class pyutils.URLParser(url, base=None)[source]

Bases: object

URL parser class similar to JavaScript URL object.

Provides methods to parse and manipulate URLs similar to the JavaScript URL API.

__init__(url, base=None)[source]

Initialize URL parser.

Parameters:
  • url (str) – URL string to parse

  • base (str | None) – Base URL for relative URLs

Examples

>>> parser = URLParser('https://example.com/path?query=value#hash')
>>> parser.hostname
'example.com'
get_query_params()[source]

Get query parameters as a dictionary.

Return type:

dict[str, str]

Returns:

Dictionary of query parameters

Examples

>>> parser = URLParser('https://example.com?name=John&age=30')
>>> params = parser.get_query_params()
>>> params['name']
'John'
property hash: str

Get the hash (fragment) of the URL.

Returns:

Hash string including ‘#’ prefix

property hostname: str

Get the hostname of the URL.

Returns:

Hostname string

property href: str

Get the complete URL.

Returns:

Complete URL string

property origin: str

Get the origin of the URL.

Returns:

Origin string (protocol + hostname + port)

property password: str

Get the password from the URL.

Returns:

Password string

property pathname: str

Get the pathname of the URL.

Returns:

Pathname string (defaults to ‘/’ if empty)

property port: str

Get the port of the URL.

Returns:

Port string (empty if default port)

property protocol: str

Get the protocol (scheme) of the URL.

Returns:

‘)

Return type:

Protocol string (e.g., ‘https

property search: str

Get the search (query) string of the URL.

Returns:

Search string including ‘?’ prefix

property username: str

Get the username from the URL.

Returns:

Username string

pyutils.add_days(dt, days)[source]

Add days to a datetime object.

Parameters:
  • dt (datetime) – Base datetime

  • days (int) – Number of days to add (can be negative)

Return type:

datetime

Returns:

New datetime with days added

Examples

>>> dt = datetime.datetime(2023, 1, 1)
>>> add_days(dt, 5)
datetime.datetime(2023, 1, 6, 0, 0)
>>> add_days(dt, -1)
datetime.datetime(2022, 12, 31, 0, 0)
pyutils.add_hours(dt, hours)[source]

Add hours to a datetime object.

Parameters:
  • dt (datetime) – Base datetime

  • hours (int) – Number of hours to add (can be negative)

Return type:

datetime

Returns:

New datetime with hours added

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 0, 0)
>>> add_hours(dt, 3)
datetime.datetime(2023, 1, 1, 15, 0)
>>> add_hours(dt, -2)
datetime.datetime(2023, 1, 1, 10, 0)
pyutils.add_minutes(dt, minutes)[source]

Add minutes to a datetime object.

Parameters:
  • dt (datetime) – Base datetime

  • minutes (int) – Number of minutes to add (can be negative)

Return type:

datetime

Returns:

New datetime with minutes added

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 30, 0)
>>> add_minutes(dt, 15)
datetime.datetime(2023, 1, 1, 12, 45)
>>> add_minutes(dt, -10)
datetime.datetime(2023, 1, 1, 12, 20)
pyutils.alphabetical(items, key_fn=None)[source]

Sort strings alphabetically (case-insensitive by default).

Parameters:
  • items (list[str]) – List of strings to sort

  • key_fn (Callable[[str], str] | None) – Optional function to extract sort key from each string

Return type:

list[str]

Returns:

New sorted list

Examples

>>> alphabetical(['banana', 'apple', 'cherry'])
['apple', 'banana', 'cherry']
>>> alphabetical(['Banana', 'apple', 'Cherry'])
['apple', 'Banana', 'Cherry']
pyutils.at(items, index)[source]

Get element at the given index, supporting negative indices.

Similar to JavaScript’s Array.prototype.at().

Parameters:
  • items (list[TypeVar(T)]) – List to access

  • index (int) – Index to access (can be negative)

Return type:

Optional[TypeVar(T)]

Returns:

Element at the index, or None if index is out of bounds

Examples

>>> at([1, 2, 3, 4], 1)
2
>>> at([1, 2, 3, 4], -1)
4
>>> at([1, 2, 3, 4], 10)
pyutils.atob(data)[source]

Decode base64 string (like JavaScript atob).

Parameters:

data (str) – Base64 string to decode

Return type:

str

Returns:

Decoded string

Raises:

ValueError – If input is not valid base64

Examples

>>> atob('aGVsbG8=')
'hello'
>>> atob('SGVsbG8sIFdvcmxkIQ==')
'Hello, World!'
pyutils.btoa(data)[source]

Encode string to base64 (like JavaScript btoa).

Parameters:

data (str) – String to encode

Return type:

str

Returns:

Base64 encoded string

Examples

>>> btoa('hello')
'aGVsbG8='
>>> btoa('Hello, World!')
'SGVsbG8sIFdvcmxkIQ=='
pyutils.build_url(protocol='http', hostname='', port=None, pathname='', query_params=None, hash_fragment='')[source]

Build a URL from components.

Parameters:
  • protocol (str) – Protocol (without colon)

  • hostname (str) – Hostname

  • port (int | None) – Port number

  • pathname (str) – Path

  • query_params (dict[str, str] | None) – Query parameters

  • hash_fragment (str) – Hash fragment

Return type:

str

Returns:

Complete URL string

Examples

>>> build_url(
...     hostname='example.com',
...     pathname='/api/users',
...     query_params={'page': '1'}
... )
'http://example.com/api/users?page=1'
pyutils.bytes_util(value)[source]

Convenience function for byte conversion.

Parameters:

value (str | int | float) – Either a byte count (int/float) or a byte string (str)

Return type:

int | str

Returns:

If input is numeric, returns formatted string If input is string, returns byte count as int

Examples

>>> bytes_util(1024)
'1 KB'
>>> bytes_util('1 KB')
1024
>>> bytes_util(1536)
'1.5 KB'
pyutils.camel_case(text)[source]

Convert string to camelCase.

Parameters:

text (str) – Input string

Return type:

str

Returns:

camelCase string

Examples

>>> camel_case('hello world')
'helloWorld'
>>> camel_case('hello-world-test')
'helloWorldTest'
>>> camel_case('hello_world_test')
'helloWorldTest'
>>> camel_case('helloWorld')
'helloWorld'
pyutils.capitalize(text)[source]

Capitalize the first letter of each word in a string.

Parameters:

text (str) – Input string

Return type:

str

Returns:

String with first letter of each word capitalized

Examples

>>> capitalize('hello world')
'Hello World'
>>> capitalize('HELLO')
'Hello'
>>> capitalize('   ')
'   '
pyutils.chunk(items, size)[source]

Split a list into chunks of specified size.

Parameters:
  • items (list[TypeVar(T)]) – List to split

  • size (int) – Size of each chunk

Return type:

list[list[TypeVar(T)]]

Returns:

List of chunks

Raises:

ValueError – If size is less than or equal to 0

Examples

>>> chunk([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]
>>> chunk(['a', 'b', 'c', 'd'], 3)
[['a', 'b', 'c'], ['d']]
pyutils.clamp(value, min_val, max_val)[source]

Clamp a value between min and max bounds.

Parameters:
  • value (int | float) – Value to clamp

  • min_val (int | float) – Minimum bound

  • max_val (int | float) – Maximum bound

Return type:

int | float

Returns:

Clamped value

Examples

>>> clamp(5, 1, 10)
5
>>> clamp(-5, 1, 10)
1
>>> clamp(15, 1, 10)
10
pyutils.copy_within(items, target, start=0, end=None)[source]

Copy array elements within the array to another position.

Similar to JavaScript’s Array.prototype.copyWithin().

Parameters:
  • items (list[TypeVar(T)]) – List to modify (modified in place)

  • target (int) – Index to copy elements to

  • start (int) – Index to start copying from

  • end (int | None) – Index to stop copying from (exclusive)

Return type:

list[TypeVar(T)]

Returns:

The modified list

Examples

>>> copy_within([1, 2, 3, 4, 5], 0, 3)
[4, 5, 3, 4, 5]
>>> copy_within([1, 2, 3, 4, 5], 2, 0, 2)
[1, 2, 1, 2, 5]
pyutils.dash_case(text)[source]

Convert string to dash-case (kebab-case).

Parameters:

text (str) – Input string

Return type:

str

Returns:

dash-case string

Examples

>>> dash_case('Hello World')
'hello-world'
>>> dash_case('helloWorld')
'hello-world'
>>> dash_case('hello_world')
'hello-world'
pyutils.debounce(wait=0.2, leading=False, trailing=True)[source]

Decorator to debounce function calls.

Parameters:
  • wait (float) – Wait time in seconds, defaults to 0.2

  • leading (bool) – Execute on leading edge, defaults to False

  • trailing (bool) – Execute on trailing edge, defaults to True

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], Debouncer]

Returns:

Debounced function

Examples

>>> @debounce(wait=0.1)
... def save_data(data):
...     print(f"Saving {data}")
>>>
>>> save_data("test1")
>>> save_data("test2")  # Only this will execute after 0.1s
pyutils.decode_base64(data)[source]

Decode base64 string to string.

Parameters:

data (str) – Base64 string to decode

Return type:

str

Returns:

Decoded string

Raises:

ValueError – If input is not valid base64

Examples

>>> decode_base64('aGVsbG8gd29ybGQ=')
'hello world'
pyutils.decode_hex(data)[source]

Decode hexadecimal string to string.

Parameters:

data (str) – Hexadecimal string to decode

Return type:

str

Returns:

Decoded string

Raises:

ValueError – If input is not valid hexadecimal

Examples

>>> decode_hex('68656c6c6f')
'hello'
pyutils.decode_uri(uri)[source]

Decode a complete URI (like JavaScript decodeURI).

Parameters:

uri (str) – URI to decode

Return type:

str

Returns:

Decoded URI

Examples

>>> decode_uri('https://example.com/path%20with%20spaces')
'https://example.com/path with spaces'
pyutils.decode_uri_component(text)[source]

Decode a URI component string (like JavaScript decodeURIComponent).

Parameters:

text (str) – String to decode

Return type:

str

Returns:

Decoded string

Raises:

ValueError – If the string contains invalid percent encoding

Examples

>>> decode_uri_component('hello%20world')
'hello world'
>>> decode_uri_component('user%40example.com')
'user@example.com'
pyutils.deep_copy(obj)[source]

Create a deep copy of an object.

Parameters:

obj (Any) – Object to copy

Return type:

Any

Returns:

Deep copy of the object

Examples

>>> original = {'a': {'b': 1}}
>>> copied = deep_copy(original)
>>> copied['a']['b'] = 2
>>> original['a']['b']
1
async pyutils.delay(value, seconds)[source]

Return a value after a delay.

Parameters:
  • value (TypeVar(T)) – Value to return after delay

  • seconds (float) – Delay in seconds

Return type:

TypeVar(T)

Returns:

The provided value after delay

Examples

>>> async def main():
...     result = await delay("hello", 0.1)
...     print(result)  # "hello" (after 0.1 seconds)
>>> # asyncio.run(main())
pyutils.diff(old_list, new_list)[source]

Find items that are in old_list but not in new_list.

Parameters:
  • old_list (list[TypeVar(T)]) – Original list

  • new_list (list[TypeVar(T)]) – New list

Return type:

list[TypeVar(T)]

Returns:

List of items that were removed (in old_list but not in new_list)

Examples

>>> diff([1, 2, 3, 4], [2, 4])
[1, 3]
>>> diff([1, 2, 3], [1, 2, 3])
[]
>>> diff([1, 1, 2, 3], [1])
[2, 3]
pyutils.encode_base64(data)[source]

Encode data to base64.

Parameters:

data (str | bytes) – Data to encode (string or bytes)

Return type:

str

Returns:

Base64 encoded string

Examples

>>> encode_base64('hello world')
'aGVsbG8gd29ybGQ='
>>> encode_base64(b'hello world')
'aGVsbG8gd29ybGQ='
pyutils.encode_hex(data)[source]

Encode data to hexadecimal.

Parameters:

data (str | bytes) – Data to encode (string or bytes)

Return type:

str

Returns:

Hexadecimal encoded string

Examples

>>> encode_hex('hello')
'68656c6c6f'
>>> encode_hex(b'hello')
'68656c6c6f'
pyutils.encode_uri(uri)[source]

Encode a complete URI (like JavaScript encodeURI).

Parameters:

uri (str) – URI to encode

Return type:

str

Returns:

Encoded URI

Examples

>>> encode_uri('https://example.com/path with spaces')
'https://example.com/path%20with%20spaces'
pyutils.encode_uri_component(text)[source]

Encode a string for use in a URI component (like JavaScript encodeURIComponent).

Parameters:

text (str) – String to encode

Return type:

str

Returns:

Encoded string

Examples

>>> encode_uri_component('hello world')
'hello%20world'
>>> encode_uri_component('user@example.com')
'user%40example.com'
pyutils.entries(items)[source]

Return array of [index, value] pairs.

Similar to JavaScript’s Array.prototype.entries().

Parameters:

items (list[TypeVar(T)]) – List to get entries from

Return type:

list[tuple[int, TypeVar(T)]]

Returns:

List of (index, value) tuples

Examples

>>> entries(['a', 'b', 'c'])
[(0, 'a'), (1, 'b'), (2, 'c')]
pyutils.escape_html(text)[source]

Escape HTML special characters.

Parameters:

text (str) – Text to escape

Return type:

str

Returns:

HTML escaped text

Examples

>>> escape_html('<div>Hello & goodbye</div>')
'&lt;div&gt;Hello &amp; goodbye&lt;/div&gt;'
>>> escape_html('"quoted" text')
'&quot;quoted&quot; text'
pyutils.every(items, predicate)[source]

Test whether all elements pass the test.

Similar to JavaScript’s Array.prototype.every().

Parameters:
  • items (list[TypeVar(T)]) – List to test

  • predicate (Callable[[TypeVar(T)], bool]) – Function to test each element

Return type:

bool

Returns:

True if all elements pass the test

Examples

>>> every([2, 4, 6, 8], lambda x: x % 2 == 0)
True
>>> every([1, 2, 3, 4], lambda x: x % 2 == 0)
False
pyutils.factorial(n)[source]

Calculate the factorial of a non-negative integer.

Parameters:

n (int) – Non-negative integer

Return type:

int

Returns:

Factorial of n

Raises:

ValueError – If n is negative

Examples

>>> factorial(5)
120
>>> factorial(0)
1
>>> factorial(1)
1
pyutils.fibonacci(n)[source]

Calculate the nth Fibonacci number.

Parameters:

n (int) – Position in Fibonacci sequence (0-indexed)

Return type:

int

Returns:

nth Fibonacci number

Raises:

ValueError – If n is negative

Examples

>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(10)
55
pyutils.fill(items, value, start=0, end=None)[source]

Fill array elements with a static value.

Similar to JavaScript’s Array.prototype.fill().

Parameters:
  • items (list[TypeVar(T)]) – List to fill (modified in place)

  • value (Any) – Value to fill with

  • start (int) – Start index

  • end (int | None) – End index (exclusive)

Return type:

list[TypeVar(T)]

Returns:

The modified list

Examples

>>> fill([1, 2, 3, 4], 0)
[0, 0, 0, 0]
>>> fill([1, 2, 3, 4], 0, 1, 3)
[1, 0, 0, 4]
async pyutils.filter_async(predicate, items, concurrency=10)[source]

Filter list using async predicate with concurrency control.

Parameters:
  • predicate (Callable[[TypeVar(T)], Awaitable[bool]]) – Async predicate function

  • items (list[TypeVar(T)]) – List of items to filter

  • concurrency (int) – Maximum concurrent executions

Return type:

list[TypeVar(T)]

Returns:

Filtered list of items

Examples

>>> async def is_even_async(n):
...     await asyncio.sleep(0.01)
...     return n % 2 == 0
>>>
>>> async def main():
...     numbers = [1, 2, 3, 4, 5, 6]
...     evens = await filter_async(is_even_async, numbers)
...     print(evens)  # [2, 4, 6]
>>> # asyncio.run(main())
pyutils.find_index(items, predicate, from_index=0)[source]

Find the index of the first element that satisfies the predicate.

Similar to JavaScript’s Array.prototype.findIndex().

Parameters:
  • items (list[TypeVar(T)]) – List to search in

  • predicate (Callable[[TypeVar(T)], bool]) – Function to test each element

  • from_index (int) – Index to start searching from

Return type:

int

Returns:

Index of first matching element, or -1 if not found

Examples

>>> find_index([1, 2, 3, 4], lambda x: x > 2)
2
>>> find_index([1, 2, 3, 4], lambda x: x > 10)
-1
pyutils.find_last_index(items, predicate)[source]

Find the index of the last element that satisfies the predicate.

Similar to JavaScript’s Array.prototype.findLastIndex().

Parameters:
  • items (list[TypeVar(T)]) – List to search in

  • predicate (Callable[[TypeVar(T)], bool]) – Function to test each element

Return type:

int

Returns:

Index of last matching element, or -1 if not found

Examples

>>> find_last_index([1, 2, 3, 2, 4], lambda x: x == 2)
3
>>> find_last_index([1, 2, 3, 4], lambda x: x > 10)
-1
pyutils.first(items, default=None)[source]

Get the first item from a list.

Parameters:
  • items (list[TypeVar(T)]) – List to get first item from

  • default (Optional[TypeVar(T)]) – Default value if list is empty

Return type:

Optional[TypeVar(T)]

Returns:

First item or default value

Examples

>>> first([1, 2, 3])
1
>>> first([], 'default')
'default'
pyutils.flat_map(items, mapper)[source]

Map each element and flatten the result.

Similar to JavaScript’s Array.prototype.flatMap().

Parameters:
  • items (list[TypeVar(T)]) – List of items to map and flatten

  • mapper (Callable[[TypeVar(T)], list[Any]]) – Function that maps each item to a list

Return type:

list[Any]

Returns:

Flattened list of mapped results

Examples

>>> flat_map([1, 2, 3], lambda x: [x, x * 2])
[1, 2, 2, 4, 3, 6]
>>> flat_map(['hello', 'world'], lambda x: list(x))
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
pyutils.flatten_dict(obj, separator='.', prefix='')[source]

Flatten a nested dictionary.

Parameters:
  • obj (dict[str, Any]) – Dictionary to flatten

  • separator (str) – Separator for nested keys, defaults to ‘.’

  • prefix (str) – Prefix for keys, defaults to ‘’

Return type:

dict[str, Any]

Returns:

Flattened dictionary

Examples

>>> flatten_dict({'a': {'b': {'c': 1}}})
{'a.b.c': 1}
>>> flatten_dict({'user': {'name': 'Alice', 'age': 25}})
{'user.name': 'Alice', 'user.age': 25}
pyutils.format_relative_time(dt, base_dt=None)[source]

Format datetime as relative time string (like ‘X minutes ago’).

Parameters:
  • dt (datetime) – Datetime to format

  • base_dt (datetime | None) – Base datetime to compare against (defaults to now)

Return type:

str

Returns:

Relative time string

Examples

>>> import datetime
>>> now = datetime.datetime.now()
>>> past = now - datetime.timedelta(minutes=5)
>>> format_relative_time(past, now)
'5 minutes ago'
pyutils.fuzzy_match(pattern, text)[source]

Calculate fuzzy match score between pattern and text.

Parameters:
  • pattern (str) – Pattern to match

  • text (str) – Text to search in

Return type:

float

Returns:

Similarity score between 0.0 and 1.0

Examples

>>> fuzzy_match('hello', 'hello')
1.0
>>> fuzzy_match('hello', 'world')
0.0
>>> fuzzy_match('hello', 'helo')
0.8
pyutils.gcd(a, b)[source]

Calculate the greatest common divisor of two integers.

Parameters:
  • a (int) – First integer

  • b (int) – Second integer

Return type:

int

Returns:

Greatest common divisor

Examples

>>> gcd(12, 8)
4
>>> gcd(17, 13)
1
>>> gcd(0, 5)
5
pyutils.generate_random_string(length=16, charset='alphanumeric')[source]

Generate a random string.

Parameters:
  • length (int) – Length of the string to generate

  • charset (str) – Character set to use (‘alphanumeric’, ‘alpha’, ‘numeric’, ‘hex’) or custom string

Return type:

str

Returns:

Random string

Examples

>>> len(generate_random_string(10))
10
>>> all(c.isalnum() for c in generate_random_string(10, 'alphanumeric'))
True
pyutils.generate_uuid()[source]

Generate a UUID string.

Return type:

str

Returns:

UUID string

Examples

>>> uuid_str = generate_uuid()
>>> len(uuid_str)
36
>>> '-' in uuid_str
True
pyutils.get_domain(url)[source]

Extract domain from URL.

Parameters:

url (str) – URL string

Return type:

str | None

Returns:

Domain string or None if invalid

Examples

>>> get_domain('https://www.example.com/path')
'www.example.com'
>>> get_domain('http://subdomain.example.org:8080/api')
'subdomain.example.org'
>>> get_domain('invalid-url')
None
pyutils.get_nested_value(obj, path, separator='.', default=None)[source]

Get a nested value from a dictionary using a path.

Parameters:
  • obj (dict[str, Any]) – Source dictionary

  • path (str) – Path to the value (e.g., ‘user.profile.name’)

  • separator (str) – Path separator, defaults to ‘.’

  • default (Any) – Default value if path not found

Return type:

Any

Returns:

Value at the specified path or default

Examples

>>> data = {'user': {'profile': {'name': 'Alice'}}}
>>> get_nested_value(data, 'user.profile.name')
'Alice'
>>> get_nested_value(data, 'user.profile.age', default=0)
0
pyutils.get_query_params(url)[source]

Extract query parameters from URL.

Parameters:

url (str) – URL string

Return type:

dict[str, str]

Returns:

Dictionary of query parameters

Examples

>>> get_query_params(
...     'https://example.com/path?foo=bar&baz=qux'
... )
{'foo': 'bar', 'baz': 'qux'}
>>> get_query_params('https://example.com/path')
{}
pyutils.get_random_int(min_val, max_val)[source]

Generate a random integer between min and max (inclusive).

Parameters:
  • min_val (int) – Minimum value (inclusive)

  • max_val (int) – Maximum value (inclusive)

Return type:

int

Returns:

Random integer between min_val and max_val

Raises:

ValueError – If min_val > max_val

Examples

>>> result = get_random_int(1, 10)
>>> 1 <= result <= 10
True
>>> get_random_int(5, 5)
5
pyutils.get_time(dt)[source]

Get timestamp in milliseconds from datetime (like JavaScript Date.getTime()).

Parameters:

dt (datetime) – Datetime object

Return type:

int

Returns:

Timestamp in milliseconds

Examples

>>> dt = datetime.datetime(2023, 1, 1, 0, 0, 0)
>>> timestamp = get_time(dt)
>>> isinstance(timestamp, int)
True
pyutils.group_by(items, key_fn)[source]

Group array elements by a key function.

Similar to JavaScript’s Object.groupBy() (proposed).

Parameters:
  • items (list[TypeVar(T)]) – List of items to group

  • key_fn (Callable[[TypeVar(T)], TypeVar(K)]) – Function to extract grouping key

Return type:

dict[TypeVar(K), list[TypeVar(T)]]

Returns:

Dictionary mapping keys to lists of items

Examples

>>> group_by(['apple', 'banana', 'apricot'], lambda x: x[0])
{'a': ['apple', 'apricot'], 'b': ['banana']}
>>> group_by([1, 2, 3, 4, 5], lambda x: x % 2)
{1: [1, 3, 5], 0: [2, 4]}
pyutils.has_intersects(list1, list2)[source]

Check if two lists have any common elements.

Parameters:
  • list1 (list[TypeVar(T)]) – First list

  • list2 (list[TypeVar(T)]) – Second list

Return type:

bool

Returns:

True if lists have common elements, False otherwise

Examples

>>> has_intersects([1, 2, 3], [3, 4, 5])
True
>>> has_intersects([1, 2], [3, 4])
False
pyutils.hash_string(text, algorithm='sha256')[source]

Generate hash of a string.

Parameters:
  • text (str) – String to hash

  • algorithm (str) – Hash algorithm (‘md5’, ‘sha1’, ‘sha256’, ‘sha512’)

Return type:

str

Returns:

Hexadecimal hash string

Raises:

ValueError – If algorithm is not supported

Examples

>>> len(hash_string('hello', 'md5'))
32
>>> len(hash_string('hello', 'sha256'))
64
pyutils.humanize_bytes(byte_count, decimals=1, binary=True)[source]

Convert bytes to human readable format.

Parameters:
  • byte_count (int | float) – Number of bytes

  • decimals (int) – Number of decimal places

  • binary (bool) – Use binary (1024) or decimal (1000) units

Return type:

str

Returns:

Human readable byte string

Examples

>>> humanize_bytes(1024)
'1 KB'
>>> humanize_bytes(1000, binary=False)
'1 KB'
>>> humanize_bytes(1536, decimals=2)
'1.50 KB'
pyutils.includes(items, search_item, from_index=0)[source]

Check if an array includes a certain value.

Similar to JavaScript’s Array.prototype.includes().

Parameters:
  • items (list[TypeVar(T)]) – List to search in

  • search_item (TypeVar(T)) – Item to search for

  • from_index (int) – Index to start searching from

Return type:

bool

Returns:

True if item is found, False otherwise

Examples

>>> includes([1, 2, 3], 2)
True
>>> includes([1, 2, 3], 4)
False
>>> includes([1, 2, 3, 2], 2, 2)
True
pyutils.is_array(value)[source]

Check if value is an array (list or tuple).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a list or tuple, False otherwise

Examples

>>> is_array([1, 2, 3])
True
>>> is_array((1, 2, 3))
True
>>> is_array('string')
False
pyutils.is_base64(text)[source]

Check if a string is valid base64.

Parameters:

text (str) – String to check

Return type:

bool

Returns:

True if valid base64, False otherwise

Examples

>>> is_base64('aGVsbG8=')
True
>>> is_base64('hello')
False
pyutils.is_boolean(value)[source]

Check if value is a boolean.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a boolean, False otherwise

Examples

>>> is_boolean(True)
True
>>> is_boolean(False)
True
>>> is_boolean(1)
False
pyutils.is_date(value)[source]

Check if value is a date/datetime object.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a date or datetime, False otherwise

Examples

>>> import datetime
>>> is_date(datetime.datetime.now())
True
>>> is_date(datetime.date.today())
True
>>> is_date('2023-01-01')
False
pyutils.is_empty(value)[source]

Check if value is empty (like JavaScript’s concept of empty).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is empty, False otherwise

Examples

>>> is_empty('')
True
>>> is_empty([])
True
>>> is_empty({})
True
>>> is_empty(set())
True
>>> is_empty(frozenset())
True
>>> is_empty(None)
True
>>> is_empty(0)
False
pyutils.is_even(number)[source]

Check if a number is even.

Parameters:

number (int) – Integer to check

Return type:

bool

Returns:

True if even, False if odd

Examples

>>> is_even(4)
True
>>> is_even(5)
False
>>> is_even(0)
True
pyutils.is_finite(value)[source]

Check if value is a finite number.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a finite number, False otherwise

Examples

>>> is_finite(123)
True
>>> is_finite(3.14)
True
>>> is_finite(float('inf'))
False
>>> is_finite(float('nan'))
False
pyutils.is_function(value)[source]

Check if value is a function or callable.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is callable, False otherwise

Examples

>>> is_function(lambda x: x)
True
>>> is_function(print)
True
>>> is_function('string')
False
pyutils.is_hex(text)[source]

Check if a string is valid hexadecimal.

Note

This function does not accept hex strings with ‘0x’ or ‘0X’ prefixes. Use int(text, 16) if you need to handle prefixed hex strings.

Parameters:

text (str) – String to check

Return type:

bool

Returns:

True if valid hexadecimal, False otherwise

Examples

>>> is_hex('68656c6c6f')
True
>>> is_hex('hello')
False
>>> is_hex('123abc')
True
>>> is_hex('0x123')  # Prefixed hex strings are rejected
False
pyutils.is_integer(value)[source]

Check if value is an integer (like JavaScript Number.isInteger).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is an integer, False otherwise

Examples

>>> is_integer(123)
True
>>> is_integer(3.0)
True
>>> is_integer(3.14)
False
>>> is_integer('123')
False
pyutils.is_json(text)[source]

Check if a string is valid JSON.

Parameters:

text (str) – String to check

Return type:

bool

Returns:

True if valid JSON, False otherwise

Examples

>>> is_json('{"name": "John"}')
True
>>> is_json('[1, 2, 3]')
True
>>> is_json('hello')
False
pyutils.is_nan(value)[source]

Check if value is NaN (Not a Number).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is NaN, False otherwise

Examples

>>> is_nan(float('nan'))
True
>>> is_nan(123)
False
>>> is_nan('string')
False
pyutils.is_null(value)[source]

Check if value is None (null in JavaScript).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is None, False otherwise

Examples

>>> is_null(None)
True
>>> is_null(0)
False
>>> is_null('')
False
pyutils.is_number(value)[source]

Check if value is a number (int or float).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a number, False otherwise

Examples

>>> is_number(123)
True
>>> is_number(3.14)
True
>>> is_number('123')
False
pyutils.is_object(value)[source]

Check if value is an object (dict in Python).

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a dict, False otherwise

Examples

>>> is_object({'key': 'value'})
True
>>> is_object([])
False
>>> is_object('string')
False
pyutils.is_odd(number)[source]

Check if a number is odd.

Parameters:

number (int) – Integer to check

Return type:

bool

Returns:

True if odd, False if even

Examples

>>> is_odd(4)
False
>>> is_odd(5)
True
>>> is_odd(0)
False
pyutils.is_prime(n)[source]

Check if a number is prime.

Parameters:

n (int) – Integer to check

Return type:

bool

Returns:

True if prime, False otherwise

Examples

>>> is_prime(7)
True
>>> is_prime(8)
False
>>> is_prime(2)
True
>>> is_prime(1)
False
pyutils.is_regex(value)[source]

Check if value is a compiled regular expression.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a compiled regex, False otherwise

Examples

>>> import re
>>> is_regex(re.compile(r'\d+'))
True
>>> is_regex(r'\d+')
False
pyutils.is_string(value)[source]

Check if value is a string.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is a string, False otherwise

Examples

>>> is_string('hello')
True
>>> is_string(123)
False
pyutils.is_undefined(value)[source]

Check if value is undefined (similar to JavaScript undefined).

In Python context, this checks for None or missing attributes.

Parameters:

value (Any) – Value to check

Return type:

bool

Returns:

True if value is None, False otherwise

Examples

>>> is_undefined(None)
True
>>> is_undefined(0)
False
pyutils.is_valid_date(date_string)[source]

Check if a string represents a valid date.

Parameters:

date_string (str) – String to check

Return type:

bool

Returns:

True if valid date, False otherwise

Examples

>>> is_valid_date('2023-01-01')
True
>>> is_valid_date('invalid-date')
False
>>> is_valid_date('2023-13-01')  # Invalid month
False
pyutils.is_valid_url(url)[source]

Check if a string is a valid URL.

Parameters:

url (str) – String to check

Return type:

bool

Returns:

True if valid URL, False otherwise

Examples

>>> is_valid_url('https://example.com')
True
>>> is_valid_url('not-a-url')
False
>>> is_valid_url('ftp://files.example.com')
True
pyutils.json_parse(text)[source]

Parse JSON string to object (like JavaScript JSON.parse).

Parameters:

text (str) – JSON string to parse

Return type:

Any

Returns:

Parsed object

Raises:

ValueError – If input is not valid JSON

Examples

>>> json_parse('{"name": "John", "age": 30}')
{'name': 'John', 'age': 30}
>>> json_parse('[1, 2, 3]')
[1, 2, 3]
pyutils.json_stringify(obj, indent=None)[source]

Convert object to JSON string (like JavaScript JSON.stringify).

Parameters:
  • obj (Any) – Object to convert

  • indent (int | None) – Indentation for pretty printing

Return type:

str

Returns:

JSON string

Examples

>>> json_stringify({'name': 'John', 'age': 30})
'{"name": "John", "age": 30}'
>>> json_stringify([1, 2, 3])
'[1, 2, 3]'
pyutils.keys(items)[source]

Return array of indices.

Similar to JavaScript’s Array.prototype.keys().

Parameters:

items (list[TypeVar(T)]) – List to get keys from

Return type:

list[int]

Returns:

List of indices

Examples

>>> keys(['a', 'b', 'c'])
[0, 1, 2]
pyutils.last(items, default=None)[source]

Get the last item from a list.

Parameters:
  • items (list[TypeVar(T)]) – List to get last item from

  • default (Optional[TypeVar(T)]) – Default value if list is empty

Return type:

Optional[TypeVar(T)]

Returns:

Last item or default value

Examples

>>> last([1, 2, 3])
3
>>> last([], 'default')
'default'
pyutils.lcm(a, b)[source]

Calculate the least common multiple of two integers.

Parameters:
  • a (int) – First integer

  • b (int) – Second integer

Return type:

int

Returns:

Least common multiple

Examples

>>> lcm(12, 8)
24
>>> lcm(3, 5)
15
>>> lcm(0, 5)
0
pyutils.lerp(start, end, t)[source]

Linear interpolation between two values.

Parameters:
  • start (int | float) – Starting value

  • end (int | float) – Ending value

  • t (float) – Interpolation factor (0.0 to 1.0)

Return type:

float

Returns:

Interpolated value

Examples

>>> lerp(0, 10, 0.5)
5.0
>>> lerp(10, 20, 0.25)
12.5
>>> lerp(5, 15, 0.0)
5.0
async pyutils.map_async(func, items, concurrency=10)[source]

Apply async function to list of items with concurrency control.

Parameters:
  • func (Callable[[TypeVar(T)], Awaitable[Any]]) – Async function to apply

  • items (list[TypeVar(T)]) – List of items to process

  • concurrency (int) – Maximum concurrent executions

Return type:

list[Any]

Returns:

List of results in order

Examples

>>> async def process_item(item):
...     await asyncio.sleep(0.1)
...     return item * 2
>>>
>>> async def main():
...     items = [1, 2, 3, 4, 5]
...     results = await map_async(process_item, items, concurrency=2)
...     print(results)  # [2, 4, 6, 8, 10]
>>> # asyncio.run(main())
pyutils.memoize(func)[source]

Decorator to memoize function results.

Parameters:

func (TypeVar(F, bound= Callable[..., Any])) – Function to memoize

Return type:

TypeVar(F, bound= Callable[..., Any])

Returns:

Memoized function

Examples

>>> @memoize
... def expensive_calculation(n):
...     print(f"Computing for {n}")
...     return n * n
>>>
>>> expensive_calculation(5)  # Prints "Computing for 5"
25
>>> expensive_calculation(5)  # Uses cached result, no print
25
pyutils.merge(*dicts)[source]

Recursively merge multiple dictionaries.

Parameters:

*dicts (dict[Any, Any]) – Dictionaries to merge

Return type:

dict[Any, Any]

Returns:

Merged dictionary

Examples

>>> merge({'a': 1}, {'b': 2})
{'a': 1, 'b': 2}
>>> merge({'a': {'x': 1}}, {'a': {'y': 2}})
{'a': {'x': 1, 'y': 2}}
>>> merge({'a': 1}, {'a': 2})
{'a': 2}
pyutils.normalize(value, min_val, max_val)[source]

Normalize a value to a 0-1 range based on min and max bounds.

Parameters:
  • value (int | float) – Value to normalize

  • min_val (int | float) – Minimum bound

  • max_val (int | float) – Maximum bound

Return type:

float

Returns:

Normalized value (0.0 to 1.0)

Raises:

ZeroDivisionError – If max_val equals min_val (zero range)

Examples

>>> normalize(5, 0, 10)
0.5
>>> normalize(25, 0, 100)
0.25
>>> normalize(0, 0, 10)
0.0
pyutils.now()[source]

Get current timestamp in milliseconds.

Similar to JavaScript Date.now().

Return type:

int

Returns:

Current timestamp in milliseconds

Examples

>>> timestamp = now()
>>> isinstance(timestamp, int)
True
>>> timestamp > 0
True
pyutils.omit(obj, keys)[source]

Create a new dictionary without the specified keys.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

  • keys (list[TypeVar(K)]) – List of keys to omit

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

New dictionary without the specified keys

Examples

>>> omit({'a': 1, 'b': 2, 'c': 3}, ['b'])
{'a': 1, 'c': 3}
>>> omit({'name': 'Alice', 'age': 25, 'city': 'NYC'}, ['age', 'city'])
{'name': 'Alice'}
pyutils.once(func)[source]

Decorator to ensure function is called only once.

Parameters:

func (TypeVar(F, bound= Callable[..., Any])) – Function to call once

Return type:

TypeVar(F, bound= Callable[..., Any])

Returns:

Function that can only be called once

Examples

>>> @once
... def initialize():
...     print("Initializing...")
...     return "initialized"
>>>
>>> initialize()  # Prints "Initializing..."
'initialized'
>>> initialize()  # Returns cached result, no print
'initialized'
pyutils.parse_bytes(byte_string, binary=True)[source]

Parse byte string to integer.

Parameters:
  • byte_string (str) – String representation of bytes

  • binary (bool) – Use binary (1024) or decimal (1000) units

Return type:

int

Returns:

Number of bytes

Examples

>>> parse_bytes('1 KB')
1024
>>> parse_bytes('1 KB', binary=False)
1000
pyutils.parse_date(date_string)[source]

Parse a date string into a datetime object (like JavaScript Date.parse()).

Parameters:

date_string (str) – Date string to parse

Return type:

datetime

Returns:

Parsed datetime object

Raises:

ValueError – If date string cannot be parsed

Examples

>>> parse_date('2023-01-01')
datetime.datetime(2023, 1, 1, 0, 0)
>>> parse_date('2023-01-01T12:30:45')
datetime.datetime(2023, 1, 1, 12, 30, 45)
pyutils.parse_float(value)[source]

Parse string to float (like JavaScript parseFloat).

Parameters:

value (Any) – String to parse

Return type:

float

Returns:

Parsed float or NaN if parsing fails

Examples

>>> parse_float('3.14')
3.14
>>> parse_float('3.14abc')
3.14
>>> import math
>>> math.isnan(parse_float('abc'))
True
pyutils.parse_int(value, radix=10)[source]

Parse string to integer (like JavaScript parseInt).

Parameters:
  • value (Any) – String to parse

  • radix (int) – Base for parsing (2-36), defaults to 10

Return type:

int | float

Returns:

Parsed integer or NaN if parsing fails

Examples

>>> parse_int('123')
123
>>> parse_int('123.45')
123
>>> parse_int('ff', 16)
255
>>> import math
>>> math.isnan(parse_int('invalid'))
True
pyutils.parse_template(template, variables)[source]

Parse template string with variable substitution.

Parameters:
  • template (str) – Template string with {variable} placeholders

  • variables (dict[str, str | int | float]) – Dictionary of variable values

Return type:

str

Returns:

Parsed string with variables substituted

Examples

>>> parse_template('Hello {name}!', {'name': 'World'})
'Hello World!'
>>> parse_template('{greeting} {name}, you are {age} years old',
...                {'greeting': 'Hi', 'name': 'Alice', 'age': 25})
'Hi Alice, you are 25 years old'
pyutils.parse_url(url, base=None)[source]

Parse a URL string into a dictionary.

Parameters:
  • url (str) – URL string to parse

  • base (str | None) – Base URL for relative URLs

Return type:

dict[str, str]

Returns:

Dictionary with URL components

Examples

>>> result = parse_url('https://example.com/path')
>>> result['hostname']
'example.com'
pyutils.pascal_case(text)[source]

Convert string to PascalCase.

Parameters:

text (str) – Input string

Return type:

str

Returns:

PascalCase string

Examples

>>> pascal_case('hello world')
'HelloWorld'
>>> pascal_case('hello-world-test')
'HelloWorldTest'
>>> pascal_case('hello_world_test')
'HelloWorldTest'
>>> pascal_case('helloWorld')
'HelloWorld'
pyutils.pick(obj, keys)[source]

Create a new dictionary with only the specified keys.

Parameters:
  • obj (dict[TypeVar(K), TypeVar(V)]) – Source dictionary

  • keys (list[TypeVar(K)]) – List of keys to pick

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

New dictionary with only the specified keys

Examples

>>> pick({'a': 1, 'b': 2, 'c': 3}, ['a', 'c'])
{'a': 1, 'c': 3}
>>> pick({'name': 'Alice', 'age': 25, 'city': 'NYC'}, ['name', 'age'])
{'name': 'Alice', 'age': 25}
async pyutils.race(*coroutines)[source]

Return the result of the first coroutine to complete.

Parameters:

*coroutines (Awaitable[TypeVar(T)]) – Coroutines to race

Return type:

TypeVar(T)

Returns:

Result of the first completed coroutine

Examples

>>> async def slow():
...     await asyncio.sleep(1)
...     return "slow"
>>>
>>> async def fast():
...     await asyncio.sleep(0.1)
...     return "fast"
>>>
>>> async def main():
...     result = await race(slow(), fast())
...     print(result)  # "fast"
>>> # asyncio.run(main())
pyutils.range_iter(start, end=None, step=1)[source]

Generate integers from start to end (exclusive).

Parameters:
  • start (int) – Starting value (or end if end is None)

  • end (int | None) – Ending value (exclusive), optional

  • step (int) – Step size, defaults to 1

Yields:

Integer values

Return type:

Generator[int, None, None]

Examples

>>> list(range_iter(3))
[0, 1, 2]
>>> list(range_iter(1, 4))
[1, 2, 3]
pyutils.range_list(start, end=None, step=1)[source]

Generate a list of integers from start to end (exclusive).

Parameters:
  • start (int) – Starting value (or end if end is None)

  • end (int | None) – Ending value (exclusive), optional

  • step (int) – Step size, defaults to 1

Return type:

list[int]

Returns:

List of integers

Examples

>>> range_list(5)
[0, 1, 2, 3, 4]
>>> range_list(2, 5)
[2, 3, 4]
>>> range_list(0, 10, 2)
[0, 2, 4, 6, 8]
async pyutils.retry_async(coro_func, max_retries=3, delay=0, backoff_factor=1, should_retry=None)[source]

Retry an async function with exponential backoff.

Parameters:
  • coro_func (Callable[[], Awaitable[TypeVar(T)]]) – Function that returns a coroutine

  • max_retries (int) – Maximum number of retry attempts

  • delay (float) – Initial delay between retries in seconds

  • backoff_factor (float) – Multiplier for delay on each retry

  • should_retry (Callable[[Exception], bool] | None) – Function to determine if error should trigger retry

Return type:

TypeVar(T)

Returns:

Result of successful execution

Raises:

Exception – Last exception if all retries failed

Examples

>>> async def unreliable_api():
...     import random
...     if random.random() < 0.7:
...         raise Exception("API Error")
...     return "success"
>>>
>>> async def main():
...     result = await retry_async(
...         unreliable_api,
...         max_retries=3,
...         delay=0.1,
...         backoff_factor=2
...     )
...     print(result)
>>> # asyncio.run(main())
pyutils.run_in_thread(func, *args, **kwargs)[source]

Run a synchronous function in a thread pool.

Parameters:
  • func (Callable[..., TypeVar(T)]) – Synchronous function to run

  • *args (Any) – Positional arguments

  • **kwargs (Any) – Keyword arguments

Return type:

Awaitable[TypeVar(T)]

Returns:

Awaitable result

Examples

>>> def cpu_intensive_task(n):
...     return sum(i * i for i in range(n))
>>>
>>> async def main():
...     result = await run_in_thread(cpu_intensive_task, 1000)
...     print(result)
>>> # asyncio.run(main())
pyutils.safe_json_stringify(obj, indent=None)[source]

Safely convert object to JSON string, removing non-serializable properties.

Parameters:
  • obj (Any) – Object to stringify

  • indent (int | None) – JSON indentation, optional

Return type:

str

Returns:

JSON string

Examples

>>> safe_json_stringify({'name': 'Alice', 'age': 25})
'{"name": "Alice", "age": 25}'
>>> import datetime
>>> data = {'name': 'Alice', 'func': lambda x: x}
>>> result = safe_json_stringify(data)
>>> 'name' in result
True
>>> 'func' in result
False
pyutils.set_nested_value(obj, path, value, separator='.')[source]

Set a nested value in a dictionary using a path.

Parameters:
  • obj (dict[str, Any]) – Target dictionary (will be modified)

  • path (str) – Path to set the value (e.g., ‘user.profile.name’)

  • value (Any) – Value to set

  • separator (str) – Path separator, defaults to ‘.’

Return type:

dict[str, Any]

Returns:

The modified dictionary

Examples

>>> data = {}
>>> set_nested_value(data, 'user.profile.name', 'Alice')
{'user': {'profile': {'name': 'Alice'}}}
>>> data
{'user': {'profile': {'name': 'Alice'}}}
pyutils.shuffle(items)[source]

Return a new list with items in random order.

Parameters:

items (list[TypeVar(T)]) – List to shuffle

Return type:

list[TypeVar(T)]

Returns:

New shuffled list

Examples

>>> original = [1, 2, 3, 4, 5]
>>> shuffled = shuffle(original)
>>> len(shuffled) == len(original)
True
>>> set(shuffled) == set(original)
True
async pyutils.sleep_async(seconds)[source]

Asynchronously sleep for the specified number of seconds.

Parameters:

seconds (float) – Number of seconds to sleep

Return type:

None

Examples

>>> import asyncio
>>> async def main():
...     await sleep_async(0.1)
...     print("Slept for 0.1 seconds")
>>> # asyncio.run(main())
pyutils.slugify(text, separator='-')[source]

Convert string to URL-friendly slug.

Parameters:
  • text (str) – Input string

  • separator (str) – Separator character, defaults to ‘-’

Return type:

str

Returns:

URL-friendly slug

Examples

>>> slugify('Hello World!')
'hello-world'
>>> slugify('This is a Test!', '_')
'this_is_a_test'
pyutils.snake_case(text)[source]

Convert string to snake_case.

Parameters:

text (str) – Input string

Return type:

str

Returns:

snake_case string

Examples

>>> snake_case('Hello World')
'hello_world'
>>> snake_case('helloWorld')
'hello_world'
>>> snake_case('hello-world')
'hello_world'
pyutils.some(items, predicate)[source]

Test whether at least one element passes the test.

Similar to JavaScript’s Array.prototype.some().

Parameters:
  • items (list[TypeVar(T)]) – List to test

  • predicate (Callable[[TypeVar(T)], bool]) – Function to test each element

Return type:

bool

Returns:

True if at least one element passes the test

Examples

>>> some([1, 2, 3, 4], lambda x: x > 3)
True
>>> some([1, 2, 3, 4], lambda x: x > 10)
False
pyutils.splice(items, start, delete_count=0, *insert_items)[source]

Change array contents by removing/replacing existing elements.

Also supports adding new elements.

Similar to JavaScript’s Array.prototype.splice().

Parameters:
  • items (list[TypeVar(T)]) – List to modify (modified in place)

  • start (int) – Index to start changing the array

  • delete_count (int) – Number of elements to remove

  • *insert_items (TypeVar(T)) – Items to insert

Return type:

list[TypeVar(T)]

Returns:

List of removed elements

Examples

>>> arr = [1, 2, 3, 4, 5]
>>> removed = splice(arr, 2, 1, 'a', 'b')
>>> arr
[1, 2, 'a', 'b', 4, 5]
>>> removed
[3]
pyutils.throttle(wait=0.2, leading=False, trailing=True)[source]

Decorator to throttle function calls.

Parameters:
  • wait (float) – Wait time in seconds, defaults to 0.2

  • leading (bool) – Execute on leading edge, defaults to False

  • trailing (bool) – Execute on trailing edge, defaults to True

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], Throttler]

Returns:

Throttled function

Examples

>>> @throttle(wait=0.1)
... def api_call(data):
...     print(f"API call with {data}")
>>>
>>> api_call("test1")  # Executes immediately
>>> api_call("test2")  # Ignored (within throttle period)
async pyutils.timeout(coro, timeout_seconds, default=None)[source]

Execute coroutine with timeout.

Parameters:
  • coro (Awaitable[TypeVar(T)]) – Coroutine to execute

  • timeout_seconds (float) – Timeout in seconds

  • default (Optional[TypeVar(T)]) – Default value to return on timeout

Return type:

TypeVar(T)

Returns:

Result of coroutine or default value

Raises:

asyncio.TimeoutError – If timeout occurs and no default provided

Examples

>>> async def slow_operation():
...     await asyncio.sleep(2)
...     return "done"
>>>
>>> async def main():
...     result = await timeout(slow_operation(), 1.0, "timeout")
...     print(result)  # "timeout"
>>> # asyncio.run(main())
pyutils.to_boolean(value)[source]

Convert value to boolean (like JavaScript Boolean() constructor).

Parameters:

value (Any) – Value to convert

Return type:

bool

Returns:

Boolean representation of value

Examples

>>> to_boolean(1)
True
>>> to_boolean(0)
False
>>> to_boolean('')
False
>>> to_boolean('hello')
True
>>> to_boolean([])
False
pyutils.to_date_string(dt)[source]

Convert datetime to date string (like JavaScript Date.toDateString()).

Parameters:

dt (datetime) – Datetime object to convert

Return type:

str

Returns:

Date string in format ‘YYYY-MM-DD’

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 30, 45)
>>> to_date_string(dt)
'2023-01-01'
pyutils.to_iso_string(dt)[source]

Convert datetime to ISO string (like JavaScript Date.toISOString()).

Parameters:

dt (datetime) – Datetime object to convert

Return type:

str

Returns:

ISO format string

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 30, 45)
>>> to_iso_string(dt)
'2023-01-01T12:30:45'
pyutils.to_number(value)[source]

Convert value to number (like JavaScript Number() constructor).

Parameters:

value (Any) – Value to convert

Return type:

int | float

Returns:

Number representation of value, or NaN if conversion fails

Examples

>>> to_number('123')
123
>>> to_number('3.14')
3.14
>>> import math
>>> math.isnan(to_number('invalid'))
True
>>> to_number(True)
1
pyutils.to_reversed(items)[source]

Return a new array with elements in reversed order.

Similar to JavaScript’s Array.prototype.toReversed().

Parameters:

items (list[TypeVar(T)]) – List to reverse

Return type:

list[TypeVar(T)]

Returns:

New list with elements in reversed order

Examples

>>> to_reversed([1, 2, 3, 4])
[4, 3, 2, 1]
>>> original = [1, 2, 3]
>>> reversed_list = to_reversed(original)
>>> original
[1, 2, 3]
pyutils.to_sorted(items, key=None, reverse=False)[source]

Return a new sorted array.

Similar to JavaScript’s Array.prototype.toSorted().

Parameters:
  • items (list[TypeVar(T)]) – List to sort

  • key (Callable[[TypeVar(T)], Any] | None) – Function to extract comparison key

  • reverse (bool) – Whether to sort in reverse order

Return type:

list[TypeVar(T)]

Returns:

New sorted list

Examples

>>> to_sorted([3, 1, 4, 1, 5])
[1, 1, 3, 4, 5]
>>> to_sorted(['banana', 'apple', 'cherry'], key=len)
['apple', 'banana', 'cherry']
pyutils.to_string(value)[source]

Convert value to string (like JavaScript String() constructor).

Parameters:

value (Any) – Value to convert

Return type:

str

Returns:

String representation of value

Examples

>>> to_string(123)
'123'
>>> to_string(True)
'True'
>>> to_string([1, 2, 3])
'[1, 2, 3]'
pyutils.to_time_string(dt)[source]

Convert datetime to time string (like JavaScript Date.toTimeString()).

Parameters:

dt (datetime) – Datetime object to convert

Returns:

MM:SS’

Return type:

Time string in format ‘HH

Examples

>>> dt = datetime.datetime(2023, 1, 1, 12, 30, 45)
>>> to_time_string(dt)
'12:30:45'
pyutils.toggle(items, item)[source]

Add item to list if not present, remove if present.

Parameters:
  • items (list[TypeVar(T)]) – List to toggle item in

  • item (TypeVar(T)) – Item to toggle

Return type:

list[TypeVar(T)]

Returns:

New list with item toggled

Examples

>>> toggle([1, 2, 3], 4)
[1, 2, 3, 4]
>>> toggle([1, 2, 3], 2)
[1, 3]
pyutils.trim(text, chars=None)[source]

Remove specified characters from both ends of string.

Parameters:
  • text (str) – Input string

  • chars (str | None) – Characters to remove, defaults to whitespace

Return type:

str

Returns:

Trimmed string

Examples

>>> trim('  hello  ')
'hello'
>>> trim('...hello...', '.')
'hello'
>>> trim('abcHELLOcba', 'abc')
'HELLO'
pyutils.truncate(text, length, suffix='...')[source]

Truncate string to specified length with optional suffix.

Parameters:
  • text (str) – Input string

  • length (int) – Maximum length

  • suffix (str) – Suffix to add if truncated, defaults to ‘…’

Return type:

str

Returns:

Truncated string

Examples

>>> truncate('Hello World', 5)
'Hello...'
>>> truncate('Hello World', 20)
'Hello World'
>>> truncate('Hello World', 8, '...')
'Hello...'
pyutils.typeof(value)[source]

Get type of value (like JavaScript typeof operator).

Parameters:

value (Any) – Value to check type of

Return type:

str

Returns:

Type string

Examples

>>> typeof('hello')
'string'
>>> typeof(123)
'number'
>>> typeof(True)
'boolean'
>>> typeof(None)
'undefined'
>>> typeof({})
'object'
>>> typeof([])
'object'
>>> typeof(lambda x: x)
'function'
pyutils.unescape_html(text)[source]

Unescape HTML entities.

Parameters:

text (str) – HTML text to unescape

Return type:

str

Returns:

Unescaped text

Examples

>>> unescape_html('&lt;div&gt;Hello &amp; goodbye&lt;/div&gt;')
'<div>Hello & goodbye</div>'
>>> unescape_html('&quot;quoted&quot; text')
'"quoted" text'
pyutils.unique(items)[source]

Remove duplicate items from a list while preserving order.

Parameters:

items (list[TypeVar(T)]) – List with potential duplicates

Return type:

list[TypeVar(T)]

Returns:

List with duplicates removed

Examples

>>> unique([1, 2, 2, 3, 1, 4])
[1, 2, 3, 4]
>>> unique(['a', 'b', 'a', 'c', 'b'])
['a', 'b', 'c']
pyutils.url_decode(text)[source]

URL decode a string (like JavaScript decodeURIComponent).

Parameters:

text (str) – String to decode

Return type:

str

Returns:

URL decoded string

Examples

>>> url_decode('hello%20world')
'hello world'
>>> url_decode('user%40example.com')
'user@example.com'
pyutils.url_encode(text)[source]

URL encode a string (like JavaScript encodeURIComponent).

Parameters:

text (str) – String to encode

Return type:

str

Returns:

URL encoded string

Examples

>>> url_encode('hello world')
'hello%20world'
>>> url_encode('user@example.com')
'user%40example.com'
pyutils.values(items)[source]

Return array of values (copy of the array).

Similar to JavaScript’s Array.prototype.values().

Parameters:

items (list[TypeVar(T)]) – List to get values from

Return type:

list[TypeVar(T)]

Returns:

Copy of the list

Examples

>>> values(['a', 'b', 'c'])
['a', 'b', 'c']
pyutils.with_item(items, index, value)[source]

Return a new array with one element changed.

Similar to JavaScript’s Array.prototype.with().

Parameters:
  • items (list[TypeVar(T)]) – Original list

  • index (int) – Index to change

  • value (TypeVar(T)) – New value

Return type:

list[TypeVar(T)]

Returns:

New list with the element changed

Examples

>>> with_item([1, 2, 3, 4], 1, 'two')
[1, 'two', 3, 4]
>>> original = [1, 2, 3]
>>> modified = with_item(original, 0, 'one')
>>> original
[1, 2, 3]
pyutils.with_retry(max_retries=3, delay=0, should_retry=None)[source]

Decorator to add retry functionality to a function.

Parameters:
  • max_retries (int) – Maximum number of retry attempts

  • delay (float) – Delay between retries in seconds

  • should_retry (Callable[[Exception], bool] | None) – Function to determine if error should trigger retry

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

Returns:

Decorated function with retry capability

Examples

>>> @with_retry(max_retries=3, delay=0.1)
... def unreliable_function():
...     import random
...     if random.random() < 0.7:
...         raise Exception("Random failure")
...     return "Success"
>>>
>>> # result = unreliable_function()  # Will retry up to 3 times
pyutils.zip_object(keys, values)[source]

Create a dictionary from lists of keys and values.

Parameters:
  • keys (list[TypeVar(K)]) – List of keys

  • values (list[TypeVar(V)]) – List of values

Return type:

dict[TypeVar(K), TypeVar(V)]

Returns:

Dictionary mapping keys to values

Examples

>>> zip_object(['a', 'b', 'c'], [1, 2, 3])
{'a': 1, 'b': 2, 'c': 3}
>>> zip_object(['name', 'age'], ['Alice', 25])
{'name': 'Alice', 'age': 25}