Skip to content

Function short-hands

utilz.shorts

Shorthands for common functions or ops and maps with specific params set

aslist(e)

Idempotently convert something to a list.

Source code in utilz/shorts.py
71
72
73
def aslist(e):
    """Idempotently convert something to a list."""
    return [e] if not isinstance(e, list) else e

asstr(e)

Idempotently convert something to a str.

Source code in utilz/shorts.py
76
77
78
def asstr(e):
    """Idempotently convert something to a str."""
    return str(e) if not isinstance(e, str) else e

checkall(func, iterme, transparent=False)

Check if all elements are func(elem) == True

Parameters:

Name Type Description Default
func callable

function that returns True or False

required
iterme iterable

iterable

required
transparent bool

return iterme instead of result if check passes, useful in pipes; Default False

False

Returns:

Name Type Description
bool

True or False

Source code in utilz/shorts.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@curry
def checkall(func, iterme, transparent=False):
    """
    Check if all elements are `func(elem) == True`

    Args:
        func (callable): function that returns True or False
        iterme (iterable): iterable
        transparent (bool, optional): return iterme instead of result if check passes, useful in pipes; Default False

    Returns:
        bool: True or False
    """

    result = all(map(func, iterme))
    if transparent and result:
        return iterme
    if transparent and not result:
        raise ValueError("Check failed")
    return result

checkany(func, iterme, transparent=False)

Check if any elements are func(elem) == True

Parameters:

Name Type Description Default
func callable

function that returns True or False

required
iterme iterable

iterable

required
transparent bool

return iterme instead of result if check passes, useful in pipes; Default False

False

Returns:

Name Type Description
bool

True or False

Source code in utilz/shorts.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@curry
def checkany(func, iterme, transparent=False):
    """
    Check if any elements are `func(elem) == True`

    Args:
        func (callable): function that returns True or False
        iterme (iterable): iterable
        transparent (bool, optional): return iterme instead of result if check passes, useful in pipes; Default False

    Returns:
        bool: True or False
    """

    result = any(map(func, iterme))
    if transparent and result:
        return iterme
    if transparent and not result:
        raise ValueError("Check failed")
    return result

discard(*args, **kwargs)

Alias for filter with invert=True

Source code in utilz/shorts.py
39
40
41
42
43
@curry
def discard(*args, **kwargs):
    """Alias for `filter` with `invert=True`"""
    invert = kwargs.pop("invert", True)
    return filter(*args, invert=invert, **kwargs)

equal(*seqs)

Checks if N args of potentionally different lengths are equal. Non-iterable args are directly compared with == Dataframes and arrays both use np.allclose() for comparison

Source code in utilz/shorts.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def equal(*seqs):
    """
    Checks if N args of potentionally different lengths are equal.
    Non-iterable args are directly compared with `==`
    Dataframes and arrays both use `np.allclose()` for comparison
    """

    if not isinstance(seqs[0], Iterable):
        return checkall(lambda e: e == seqs[0], seqs)

    if isinstance(seqs[0], pd.DataFrame):
        return checkall(lambda e: np.allclose(e.to_numpy(), seqs[0].to_numpy()), seqs)

    if isinstance(seqs[0], np.ndarray):
        return checkall(lambda e: np.allclose(e, seqs[0]), seqs)

    # For other sequence types we can be lazy
    return not any(diff(*seqs, default=object()))

isempty(iterme)

Check if iterable is empty

Source code in utilz/shorts.py
81
82
83
def isempty(iterme: Iterable):
    """Check if iterable is empty"""
    return len(iterme) == 0

keep(*args, **kwargs)

Alias for filter with invert=False

Source code in utilz/shorts.py
32
33
34
35
36
@curry
def keep(*args, **kwargs):
    """Alias for `filter` with `invert=False`"""
    invert = kwargs.pop("invert", False)
    return filter(*args, invert=invert, **kwargs)

seq(*args)

Enumerated list

Source code in utilz/shorts.py
46
47
48
def seq(*args):
    """Enumerated `list`"""
    return list(range(*args))

sort(iterme, **kwargs)

Alias for sorted()

Source code in utilz/shorts.py
26
27
28
29
@curry
def sort(iterme: Iterable, **kwargs):
    """Alias for `sorted()`"""
    return sorted(iterme, **kwargs)

transpose(nested_iterable)

Flips the nesting on a nested iterable, e.g. a 3 item iterable containing 2 item iterables becomes a 2 item iterable containing 3 item iterables. Tries to preserve the class of the input otherwise returns a list.

Parameters:

Name Type Description Default
nested_iterable Iterable

an iterable of iterables

required

Returns:

Name Type Description
iterable

transposed nsted iterable

Source code in utilz/shorts.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@curry
def transpose(nested_iterable: Iterable):
    """
    Flips the nesting on a nested iterable, e.g. a 3 item iterable
    containing 2 item iterables becomes a 2 item iterable containing
    3 item iterables. Tries to preserve the class of the input otherwise
    returns a list.

    Args:
        nested_iterable (Iterable): an iterable of iterables

    Returns:
        iterable: transposed nsted iterable
    """
    out = []
    for i in range(len(nested_iterable[0])):
        out.append([elem[i] for elem in nested_iterable])
    try:
        return nested_iterable.__class__(out)
    except Exception:
        return out