Skip to content

core_utils

Core utility APIs with no local dependencies.

This module provides general-purpose helper functions and classes for common operations such as object cloning, sequence manipulation, dictionary merging, signature comparison, revision tracking, and type casting. These utilities have no dependencies on other py_misc_utils modules.

Classes:

Name Description
RevDb

Tracks version numbers for named resources.

Main APIs

ident, noop, object_context, args, is_builtin_function, isdict, refcount, denone, vfind, seqfirst, iter_next, enum_values, idx_expand, is_sequence, expand, range_split, partition, is_iterator, as_iterator, dmerge, dict_extract, str_to_type, cast, infer_value, splitstrip, separate, root_module, parent_module, ns_lookup, index_select, lindex, append_if_missing, size_str, maybe_call, maybe_call_dv, unique, enum_max, enum_bits, signature, equal_signature, genhash, equal, build_object, clone, is_namedtuple, new_with, make_ntuple, splice_iter, get_property, data_rewrite

StringTable

Interns strings, returning a canonical instance for each unique string.

The same string object is returned for repeated calls with equal content, enabling fast identity comparison.

Source code in py_misc_utils/core_utils.py
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
class StringTable:
  """Interns strings, returning a canonical instance for each unique string.

  The same string object is returned for repeated calls with equal content,
  enabling fast identity comparison.
  """

  def __init__(self):
    """Initializes an empty string table."""
    self._tbl = dict()

  def __len__(self):
    """Return the number of interned strings."""
    return len(self._tbl)

  def add(self, s):
    """Interns a string, returning the canonical instance.

    Args:
      s: The string to intern.

    Returns:
      The canonical string instance for ``s``.
    """
    x = self._tbl.get(s)
    if x is None:
      self._tbl[s] = x = s

    return x

add(s)

Interns a string, returning the canonical instance.

Parameters:

Name Type Description Default
s

The string to intern.

required

Returns:

Type Description

The canonical string instance for s.

Source code in py_misc_utils/core_utils.py
952
953
954
955
956
957
958
959
960
961
962
963
964
965
def add(self, s):
  """Interns a string, returning the canonical instance.

  Args:
    s: The string to intern.

  Returns:
    The canonical string instance for ``s``.
  """
  x = self._tbl.get(s)
  if x is None:
    self._tbl[s] = x = s

  return x

ValueList

Bases: list

A list subclass used to hold multiple values under a single dict key.

Used by dict_add to accumulate values when the same key is added multiple times.

Source code in py_misc_utils/core_utils.py
968
969
970
971
972
class ValueList(list):
  """A list subclass used to hold multiple values under a single dict key.

  Used by dict_add to accumulate values when the same key is added multiple times.
  """

RevGen

Generator of monotonically increasing revisions per named resource.

Names are stored in an in-memory RevDb, so the revision numbers are process-local unless a user-provided database is given at init time.

Parameters:

Name Type Description Default
fmt

Format string of the generated names (default: '{name}_{ver}').

None
revbase

Starting revision number (default: 0).

0
Source code in py_misc_utils/core_utils.py
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
class RevGen:
  """Generator of monotonically increasing revisions per named resource.

  Names are stored in an in-memory RevDb, so the revision numbers are
  process-local unless a user-provided database is given at init time.

  Args:
    fmt: Format string of the generated names (default: '{name}_{ver}').
    revbase: Starting revision number (default: 0).
  """

  def __init__(self, fmt=None, revbase=0):
    """Initializes a RevGen instance.

    Args:
      fmt: Format string for generated names. Defaults to '{name}_{ver}'.
      revbase: Starting version number (default 0).
    """
    self._fmt = fmt or '{name}_{ver}'
    self._revbase = revbase
    self._revdb = dict()

  def getver(self, name, defval=None):
    """Returns the current version number for a name.

    Args:
      name: The resource name.
      defval: Value returned if the name has no version recorded yet.

    Returns:
      The current version number for ``name``, or ``defval`` if not found.
    """
    return self._revdb.get(name, defval)

  def newver(self, name):
    """Increments and returns the version number for a name.

    Args:
      name: The resource name.

    Returns:
      The new (incremented) version number for ``name``.
    """
    ver = self._revdb.get(name, self._revbase)
    self._revdb[name] = ver + 1

    return ver

  def newname(self, name, shortzero=False):
    """Generates a versioned name for a resource.

    Args:
      name: The base resource name.
      shortzero: If True and the version is 0, returns just ``name`` without
        a version suffix.

    Returns:
      A formatted name using ``_fmt``, or just ``name`` if shortzero and
      version is 0.
    """
    ver = self.newver(name)

    return self._fmt.format(name=name, ver=ver) if ver != 0 or not shortzero else name

getver(name, defval=None)

Returns the current version number for a name.

Parameters:

Name Type Description Default
name

The resource name.

required
defval

Value returned if the name has no version recorded yet.

None

Returns:

Type Description

The current version number for name, or defval if not found.

Source code in py_misc_utils/core_utils.py
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
def getver(self, name, defval=None):
  """Returns the current version number for a name.

  Args:
    name: The resource name.
    defval: Value returned if the name has no version recorded yet.

  Returns:
    The current version number for ``name``, or ``defval`` if not found.
  """
  return self._revdb.get(name, defval)

newver(name)

Increments and returns the version number for a name.

Parameters:

Name Type Description Default
name

The resource name.

required

Returns:

Type Description

The new (incremented) version number for name.

Source code in py_misc_utils/core_utils.py
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
def newver(self, name):
  """Increments and returns the version number for a name.

  Args:
    name: The resource name.

  Returns:
    The new (incremented) version number for ``name``.
  """
  ver = self._revdb.get(name, self._revbase)
  self._revdb[name] = ver + 1

  return ver

newname(name, shortzero=False)

Generates a versioned name for a resource.

Parameters:

Name Type Description Default
name

The base resource name.

required
shortzero

If True and the version is 0, returns just name without a version suffix.

False

Returns:

Type Description

A formatted name using _fmt, or just name if shortzero and

version is 0.

Source code in py_misc_utils/core_utils.py
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
def newname(self, name, shortzero=False):
  """Generates a versioned name for a resource.

  Args:
    name: The base resource name.
    shortzero: If True and the version is 0, returns just ``name`` without
      a version suffix.

  Returns:
    A formatted name using ``_fmt``, or just ``name`` if shortzero and
    version is 0.
  """
  ver = self.newver(name)

  return self._fmt.format(name=name, ver=ver) if ver != 0 or not shortzero else name

ident(x)

Returns the input value unchanged.

Parameters:

Name Type Description Default
x

Any object to return as-is.

required

Returns:

Type Description

The same object passed as x.

Source code in py_misc_utils/core_utils.py
40
41
42
43
44
45
46
47
48
49
def ident(x):
  """Returns the input value unchanged.

  Args:
    x: Any object to return as-is.

  Returns:
    The same object passed as ``x``.
  """
  return x

noop(*args, **kwargs)

Does nothing, accepts any arguments.

Useful as a placeholder callback or default function.

Source code in py_misc_utils/core_utils.py
52
53
54
55
56
def noop(*args, **kwargs):
  """Does nothing, accepts any arguments.

  Useful as a placeholder callback or default function.
  """

object_context(sobj, **kwargs)

Creates a SimpleNamespace from an object's attributes plus extra kwargs.

Parameters:

Name Type Description Default
sobj

An object with a __dict__ attribute.

required
**kwargs

Additional key-value pairs to merge into the namespace.

{}

Returns:

Type Description

A types.SimpleNamespace combining the object's attributes and kwargs.

Source code in py_misc_utils/core_utils.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def object_context(sobj, **kwargs):
  """Creates a SimpleNamespace from an object's attributes plus extra kwargs.

  Args:
    sobj: An object with a ``__dict__`` attribute.
    **kwargs: Additional key-value pairs to merge into the namespace.

  Returns:
    A ``types.SimpleNamespace`` combining the object's attributes and kwargs.
  """
  ctx_args = vars(sobj).copy()
  ctx_args.update(**kwargs)

  return types.SimpleNamespace(**ctx_args)

args(*uargs, **kwargs)

Returns positional and keyword arguments as a tuple.

Parameters:

Name Type Description Default
*uargs

Positional arguments.

()
**kwargs

Keyword arguments.

{}

Returns:

Type Description

A tuple of (uargs, kwargs).

Source code in py_misc_utils/core_utils.py
75
76
77
78
79
80
81
82
83
84
85
def args(*uargs, **kwargs):
  """Returns positional and keyword arguments as a tuple.

  Args:
    *uargs: Positional arguments.
    **kwargs: Keyword arguments.

  Returns:
    A tuple of ``(uargs, kwargs)``.
  """
  return uargs, kwargs

is_builtin_function(obj)

Checks whether an object is a built-in function type.

Parameters:

Name Type Description Default
obj

The object to check.

required

Returns:

Type Description

True if obj is a types.BuiltinFunctionType, False otherwise.

Source code in py_misc_utils/core_utils.py
88
89
90
91
92
93
94
95
96
97
def is_builtin_function(obj):
  """Checks whether an object is a built-in function type.

  Args:
    obj: The object to check.

  Returns:
    True if ``obj`` is a ``types.BuiltinFunctionType``, False otherwise.
  """
  return isinstance(obj, types.BuiltinFunctionType)

isdict(value)

Checks whether a value is a mapping type.

Parameters:

Name Type Description Default
value

The object to check.

required

Returns:

Type Description

True if value is a collections.abc.Mapping, False otherwise.

Source code in py_misc_utils/core_utils.py
100
101
102
103
104
105
106
107
108
109
def isdict(value):
  """Checks whether a value is a mapping type.

  Args:
    value: The object to check.

  Returns:
    True if ``value`` is a ``collections.abc.Mapping``, False otherwise.
  """
  return isinstance(value, collections.abc.Mapping)

refcount(obj)

Returns the reference count of an object, adjusted for temporary frames.

Parameters:

Name Type Description Default
obj

The object whose reference count is requested.

required

Returns:

Type Description

The reference count minus 2 (to account for the internal call frame

and sys.getrefcount's own reference).

Source code in py_misc_utils/core_utils.py
112
113
114
115
116
117
118
119
120
121
122
123
def refcount(obj):
  """Returns the reference count of an object, adjusted for temporary frames.

  Args:
    obj: The object whose reference count is requested.

  Returns:
    The reference count minus 2 (to account for the internal call frame
    and ``sys.getrefcount``'s own reference).
  """
  # Discard 2 frame references (our own, and the sys.getrefcount() one).
  return sys.getrefcount(obj) - 2

denone(**kwargs)

Returns kwargs filtered to exclude None values.

Parameters:

Name Type Description Default
**kwargs

Keyword arguments to filter.

{}

Returns:

Type Description

A dict containing only entries whose value is not None.

Source code in py_misc_utils/core_utils.py
126
127
128
129
130
131
132
133
134
135
def denone(**kwargs):
  """Returns kwargs filtered to exclude None values.

  Args:
    **kwargs: Keyword arguments to filter.

  Returns:
    A dict containing only entries whose value is not None.
  """
  return {k: v for k, v in kwargs.items() if v is not None}

vfind(mem, b)

Searches a memoryview/bytes for the first occurrence of a byte pattern.

Parameters:

Name Type Description Default
mem

A bytes-like object to search within.

required
b

The byte pattern to search for.

required

Returns:

Type Description

The index of the first match, or -1 if not found.

Source code in py_misc_utils/core_utils.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def vfind(mem, b):
  """Searches a memoryview/bytes for the first occurrence of a byte pattern.

  Args:
    mem: A bytes-like object to search within.
    b: The byte pattern to search for.

  Returns:
    The index of the first match, or -1 if not found.
  """
  # Hmmm, a memoryview() should really have a find() API...
  m = re.search(b, mem)

  return m.start() if m is not None else -1

seqfirst(s)

Returns the first element of an iterable.

Parameters:

Name Type Description Default
s

An iterable object.

required

Returns:

Type Description

The first item yielded by iter(s).

Raises:

Type Description
StopIteration

If the iterable is empty.

Source code in py_misc_utils/core_utils.py
154
155
156
157
158
159
160
161
162
163
164
165
166
def seqfirst(s):
  """Returns the first element of an iterable.

  Args:
    s: An iterable object.

  Returns:
    The first item yielded by ``iter(s)``.

  Raises:
    StopIteration: If the iterable is empty.
  """
  return next(iter(s))

iter_next(it, defval=None)

Returns the next item from an iterator, or a default if exhausted.

Parameters:

Name Type Description Default
it

An iterator object.

required
defval

Value to return when the iterator is exhausted (default None).

None

Returns:

Type Description

The next item from it, or defval if StopIteration is raised.

Source code in py_misc_utils/core_utils.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def iter_next(it, defval=None):
  """Returns the next item from an iterator, or a default if exhausted.

  Args:
    it: An iterator object.
    defval: Value to return when the iterator is exhausted (default None).

  Returns:
    The next item from ``it``, or ``defval`` if StopIteration is raised.
  """
  try:
    return next(it)
  except StopIteration:
    return defval

enum_values(obj)

Yields (key, value) pairs from a mapping or object attributes.

Parameters:

Name Type Description Default
obj

A mapping (dict-like) or an object with attributes.

required

Yields:

Type Description

Tuples of (key, value) for each entry in the object.

Source code in py_misc_utils/core_utils.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def enum_values(obj):
  """Yields (key, value) pairs from a mapping or object attributes.

  Args:
    obj: A mapping (dict-like) or an object with attributes.

  Yields:
    Tuples of ``(key, value)`` for each entry in the object.
  """
  if isdict(obj):
    for k, v in obj.items():
      yield k, v
  else:
    for k, v in vars(obj):
      yield k, v

idx_expand(data, idx, filler=None)

Ensures a list is long enough to index at position idx.

Parameters:

Name Type Description Default
data

A list to expand in place if needed.

required
idx

The target index that must be valid after expansion.

required
filler

Value used to fill new slots (default None).

None

Returns:

Type Description

The (possibly expanded) data list.

Source code in py_misc_utils/core_utils.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def idx_expand(data, idx, filler=None):
  """Ensures a list is long enough to index at position ``idx``.

  Args:
    data: A list to expand in place if needed.
    idx: The target index that must be valid after expansion.
    filler: Value used to fill new slots (default None).

  Returns:
    The (possibly expanded) ``data`` list.
  """
  if idx >= len(data):
    data = data + [filler] * (idx + 1 - len(data))

  return data

is_sequence(v)

Checks whether a value is a sequence type (list, tuple, or generator).

Parameters:

Name Type Description Default
v

The object to check.

required

Returns:

Type Description

True if v is a list, tuple, or generator type, False otherwise.

Source code in py_misc_utils/core_utils.py
222
223
224
225
226
227
228
229
230
231
def is_sequence(v):
  """Checks whether a value is a sequence type (list, tuple, or generator).

  Args:
    v: The object to check.

  Returns:
    True if ``v`` is a list, tuple, or generator type, False otherwise.
  """
  return isinstance(v, _SEQUENCE_TYPES)

expand(data, n)

Returns data as-is if it is a sequence, otherwise repeats it n times.

Parameters:

Name Type Description Default
data

A value or sequence to check.

required
n

Number of repetitions if data is not a sequence.

required

Returns:

Type Description

data if it is a sequence, otherwise a tuple of data repeated n times.

Source code in py_misc_utils/core_utils.py
234
235
236
237
238
239
240
241
242
243
244
def expand(data, n):
  """Returns data as-is if it is a sequence, otherwise repeats it n times.

  Args:
    data: A value or sequence to check.
    n: Number of repetitions if ``data`` is not a sequence.

  Returns:
    ``data`` if it is a sequence, otherwise a tuple of ``data`` repeated n times.
  """
  return data if is_sequence(data) else (data,) * n

range_split(n, split, minsize, reverse=False)

Splits a range [0, n) into chunks of size split.

Parameters:

Name Type Description Default
n

Total size of the range.

required
split

Chunk size.

required
minsize

Minimum size for the last chunk; if smaller, it is merged.

required
reverse

If True, returns chunks in reverse order.

False

Returns:

Type Description

A tuple of (start, end) tuples describing each chunk.

Source code in py_misc_utils/core_utils.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def range_split(n, split, minsize, reverse=False):
  """Splits a range [0, n) into chunks of size ``split``.

  Args:
    n: Total size of the range.
    split: Chunk size.
    minsize: Minimum size for the last chunk; if smaller, it is merged.
    reverse: If True, returns chunks in reverse order.

  Returns:
    A tuple of (start, end) tuples describing each chunk.
  """
  splits = list(range(0, n, split))
  if len(splits) > 1 and (n - splits[-1]) < minsize:
    splits.pop()

  rsplits = []
  for i, base in enumerate(splits):
    top = splits[i + 1] if (i + 1) < len(splits) else n
    rsplits.append((base, top))

  return tuple(reversed(rsplits)) if reverse else tuple(rsplits)

partition(data, n)

Partitions data into n interleaved parts.

Parameters:

Name Type Description Default
data

A sequence to partition.

required
n

Number of parts.

required

Returns:

Type Description

A tuple of n tuples, where part i contains elements at indices i, i+n, i+2n, ...

Source code in py_misc_utils/core_utils.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def partition(data, n):
  """Partitions data into n interleaved parts.

  Args:
    data: A sequence to partition.
    n: Number of parts.

  Returns:
    A tuple of n tuples, where part i contains elements at indices i, i+n, i+2n, ...
  """
  parts = []
  for i in range(n):
    parts.append(tuple(data[j] for j in range(i, len(data), n)))

  return tuple(parts)

is_iterator(obj)

Checks whether an object is an iterator (has iter and next).

Parameters:

Name Type Description Default
obj

The object to check.

required

Returns:

Type Description

True if obj is an iterator, False otherwise.

Source code in py_misc_utils/core_utils.py
288
289
290
291
292
293
294
295
296
297
def is_iterator(obj):
  """Checks whether an object is an iterator (has __iter__ and __next__).

  Args:
    obj: The object to check.

  Returns:
    True if ``obj`` is an iterator, False otherwise.
  """
  return hasattr(obj, '__iter__') and hasattr(obj, '__next__')

as_iterator(obj)

Returns obj if it is an iterator, otherwise wraps it in a single-item iterator.

Parameters:

Name Type Description Default
obj

An object to convert to an iterator.

required

Returns:

Type Description

obj if it is already an iterator, otherwise iter([obj]).

Source code in py_misc_utils/core_utils.py
300
301
302
303
304
305
306
307
308
309
def as_iterator(obj):
  """Returns obj if it is an iterator, otherwise wraps it in a single-item iterator.

  Args:
    obj: An object to convert to an iterator.

  Returns:
    ``obj`` if it is already an iterator, otherwise ``iter([obj])``.
  """
  return obj if is_iterator(obj) else iter([obj])

dmerge(*args)

Merges multiple dictionaries into one.

Parameters:

Name Type Description Default
*args

Dictionaries to merge. Later dictionaries override earlier ones.

()

Returns:

Type Description

A single dict containing all key-value pairs from the inputs.

Source code in py_misc_utils/core_utils.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def dmerge(*args):
  """Merges multiple dictionaries into one.

  Args:
    *args: Dictionaries to merge. Later dictionaries override earlier ones.

  Returns:
    A single dict containing all key-value pairs from the inputs.
  """
  mdict = dict()
  for d in args:
    mdict.update(d)

  return mdict

dict_extract(d, prefix=None, rx=None)

Extracts entries from a dict whose keys match a regex pattern.

Parameters:

Name Type Description Default
d

The source dictionary.

required
prefix

A string prefix used to build the regex if rx is not given.

None
rx

An optional regex pattern with one capture group. If None, defaults to '{prefix}(.*)'.

None

Returns:

Type Description

A new dict with captured groups as keys and original values as values.

Source code in py_misc_utils/core_utils.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def dict_extract(d, prefix=None, rx=None):
  """Extracts entries from a dict whose keys match a regex pattern.

  Args:
    d: The source dictionary.
    prefix: A string prefix used to build the regex if ``rx`` is not given.
    rx: An optional regex pattern with one capture group. If None, defaults
      to ``'{prefix}(.*)'``.

  Returns:
    A new dict with captured groups as keys and original values as values.
  """
  if rx is None:
    rx = f'{prefix}(.*)'
  xd = dict()
  for k, v in d.items():
    m = re.match(rx, k)
    if m:
      xd[m.group(1)] = v

  return xd

dget(sdict, name, defval, dtype=None)

Gets a value from a dict with optional type coercion.

Parameters:

Name Type Description Default
sdict

The source dictionary.

required
name

The key to look up.

required
defval

Default value returned if the key is missing.

required
dtype

Optional type to cast the value to. If None and defval is not None, the type of defval is used.

None

Returns:

Type Description

The value for name (cast to dtype if applicable), or defval if

the key is missing.

Source code in py_misc_utils/core_utils.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def dget(sdict, name, defval, dtype=None):
  """Gets a value from a dict with optional type coercion.

  Args:
    sdict: The source dictionary.
    name: The key to look up.
    defval: Default value returned if the key is missing.
    dtype: Optional type to cast the value to. If None and defval is not None,
      the type of defval is used.

  Returns:
    The value for ``name`` (cast to dtype if applicable), or ``defval`` if
    the key is missing.
  """
  v = sdict.get(name, _NONE)
  if v is _NONE:
    return defval

  if dtype is None and defval is not None:
    dtype = type(defval)

  return dtype(v) if v is not None and dtype is not None else v

to_type(v, vtype)

Casts a value to a given type, parsing strings via YAML when needed.

Parameters:

Name Type Description Default
v

The value to cast.

required
vtype

The target type (e.g., int, float, list, tuple).

required

Returns:

Type Description

The value cast to vtype.

Source code in py_misc_utils/core_utils.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def to_type(v, vtype):
  """Casts a value to a given type, parsing strings via YAML when needed.

  Args:
    v: The value to cast.
    vtype: The target type (e.g., int, float, list, tuple).

  Returns:
    The value cast to ``vtype``.
  """
  if isinstance(v, str):
    if vtype in (list, tuple):
      m = re.match(r'\s*\((.*)\)\s*$', v)
      if m:
        v = f'[{m.group(1)}]'
      elif not re.match(r'\s*\[.*\]\s*$', v):
        v = f'[{v}]'

    v = yaml.safe_load(v)

  return vtype(v)

cast(v, vtype)

Casts a value to a type, returning None if the value is None.

Parameters:

Name Type Description Default
v

The value to cast.

required
vtype

The target type.

required

Returns:

Type Description

The value cast to vtype, or None if v is None.

Source code in py_misc_utils/core_utils.py
398
399
400
401
402
403
404
405
406
407
408
def cast(v, vtype):
  """Casts a value to a type, returning None if the value is None.

  Args:
    v: The value to cast.
    vtype: The target type.

  Returns:
    The value cast to ``vtype``, or None if ``v`` is None.
  """
  return to_type(v, vtype) if v is not None else None

infer_value(v, vtype=None)

Infers and casts a value using YAML parsing or an explicit type.

Parameters:

Name Type Description Default
v

The value to interpret.

required
vtype

Optional explicit type to cast to. If None, YAML parsing is used.

None

Returns:

Type Description

The parsed or cast value.

Source code in py_misc_utils/core_utils.py
411
412
413
414
415
416
417
418
419
420
421
def infer_value(v, vtype=None):
  """Infers and casts a value using YAML parsing or an explicit type.

  Args:
    v: The value to interpret.
    vtype: Optional explicit type to cast to. If None, YAML parsing is used.

  Returns:
    The parsed or cast value.
  """
  return yaml.safe_load(v) if vtype is None else to_type(v, vtype)

splitstrip(data, sep)

Splits a string by a separator and strips whitespace from each part.

Parameters:

Name Type Description Default
data

The string to split.

required
sep

The separator string.

required

Returns:

Type Description

A tuple of stripped substrings.

Source code in py_misc_utils/core_utils.py
424
425
426
427
428
429
430
431
432
433
434
def splitstrip(data, sep):
  """Splits a string by a separator and strips whitespace from each part.

  Args:
    data: The string to split.
    sep: The separator string.

  Returns:
    A tuple of stripped substrings.
  """
  return tuple(s.strip() for s in data.split(sep))

separate(data, sep, reverse=False, filler=_NONE)

Splits a string at the first (or last) occurrence of a separator.

Parameters:

Name Type Description Default
data

The string to split.

required
sep

The separator substring.

required
reverse

If True, splits at the last occurrence (rfind). Otherwise splits at the first (find).

False
filler

Value returned as the second element if sep is not found. If _NONE and sep is not found, returns only the stripped string.

_NONE

Returns:

Type Description

A tuple (before, after) with stripped parts. If sep is not found and

filler is _NONE, returns (stripped_data,).

Source code in py_misc_utils/core_utils.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def separate(data, sep, reverse=False, filler=_NONE):
  """Splits a string at the first (or last) occurrence of a separator.

  Args:
    data: The string to split.
    sep: The separator substring.
    reverse: If True, splits at the last occurrence (rfind). Otherwise splits
      at the first (find).
    filler: Value returned as the second element if sep is not found. If _NONE
      and sep is not found, returns only the stripped string.

  Returns:
    A tuple ``(before, after)`` with stripped parts. If sep is not found and
    filler is _NONE, returns ``(stripped_data,)``.
  """
  pos = data.rfind(sep) if reverse else data.find(sep)
  if pos < 0:
    if filler is not _NONE:
      return data.strip(), filler
    else:
      return data.strip(),

  return data[:pos].strip(), data[pos + 1:].strip()

root_module(modname)

Returns the root (top-level) module name from a dotted module path.

Parameters:

Name Type Description Default
modname

A dotted module name string.

required

Returns:

Type Description

The first component before the first dot.

Source code in py_misc_utils/core_utils.py
462
463
464
465
466
467
468
469
470
471
def root_module(modname):
  """Returns the root (top-level) module name from a dotted module path.

  Args:
    modname: A dotted module name string.

  Returns:
    The first component before the first dot.
  """
  return separate(modname, '.')[0]

parent_module(modname)

Returns the parent module name from a dotted module path.

Parameters:

Name Type Description Default
modname

A dotted module name string.

required

Returns:

Type Description

The module name without the last component after the final dot.

Source code in py_misc_utils/core_utils.py
474
475
476
477
478
479
480
481
482
483
def parent_module(modname):
  """Returns the parent module name from a dotted module path.

  Args:
    modname: A dotted module name string.

  Returns:
    The module name without the last component after the final dot.
  """
  return separate(modname, '.', reverse=True)[0]

ns_lookup(key, mappings)

Looks up a dotted key across a sequence of namespaces.

Parameters:

Name Type Description Default
key

A dot-separated key string.

required
mappings

A sequence of dict-like or object namespaces to search.

required

Returns:

Type Description

The value found in the first namespace where the full key path resolves,

or None if not found in any namespace.

Source code in py_misc_utils/core_utils.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def ns_lookup(key, mappings):
  """Looks up a dotted key across a sequence of namespaces.

  Args:
    key: A dot-separated key string.
    mappings: A sequence of dict-like or object namespaces to search.

  Returns:
    The value found in the first namespace where the full key path resolves,
    or None if not found in any namespace.
  """
  kparts = key.split('.')
  for ns in mappings:
    for part in kparts:
      if isdict(ns):
        ns = ns.get(part)
      else:
        ns = getattr(ns, part, None)
      if ns is None:
        break

    if ns is not None:
      return ns

index_select(arr, idx)

Selects elements from an array using a slice or list of indices.

Parameters:

Name Type Description Default
arr

A sequence to index into.

required
idx

A slice object or a list/tuple of integer indices.

required

Returns:

Type Description

The sliced subsequence, or a list of selected elements.

Source code in py_misc_utils/core_utils.py
511
512
513
514
515
516
517
518
519
520
521
def index_select(arr, idx):
  """Selects elements from an array using a slice or list of indices.

  Args:
    arr: A sequence to index into.
    idx: A slice object or a list/tuple of integer indices.

  Returns:
    The sliced subsequence, or a list of selected elements.
  """
  return arr[idx] if isinstance(idx, slice) else [arr[i] for i in idx]

lindex(l, e, start=0, end=None)

Returns the index of an element in a list, or -1 if not found.

Parameters:

Name Type Description Default
l

The list to search.

required
e

The element to find.

required
start

The starting index (inclusive).

0
end

The ending index (exclusive). If None, searches to the end.

None

Returns:

Type Description

The index of the first occurrence of e, or -1 if not found.

Source code in py_misc_utils/core_utils.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def lindex(l, e, start=0, end=None):
  """Returns the index of an element in a list, or -1 if not found.

  Args:
    l: The list to search.
    e: The element to find.
    start: The starting index (inclusive).
    end: The ending index (exclusive). If None, searches to the end.

  Returns:
    The index of the first occurrence of ``e``, or -1 if not found.
  """
  try:
    return l.index(e, start, end if end is not None else len(l))
  except ValueError:
    return -1

append_if_missing(arr, elem)

Appends an element to a list if it is not already present.

Parameters:

Name Type Description Default
arr

The list to modify in place.

required
elem

The element to append if missing.

required
Source code in py_misc_utils/core_utils.py
542
543
544
545
546
547
548
549
550
def append_if_missing(arr, elem):
  """Appends an element to a list if it is not already present.

  Args:
    arr: The list to modify in place.
    elem: The element to append if missing.
  """
  if elem not in arr:
    arr.append(elem)

size_str(size)

Formats a byte size into a human-readable string.

Parameters:

Name Type Description Default
size

The size in bytes.

required

Returns:

Type Description

A string like '1024 KB' or '5.00 MB' using the largest unit

that keeps the value under 1024.

Source code in py_misc_utils/core_utils.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def size_str(size):
  """Formats a byte size into a human-readable string.

  Args:
    size: The size in bytes.

  Returns:
    A string like ``'1024 KB'`` or ``'5.00 MB'`` using the largest unit
    that keeps the value under 1024.
  """
  syms = ('B', 'KB', 'MB', 'GB', 'TB')

  for i, sym in enumerate(syms):
    if size < 1024:
      return f'{size} {sym}' if i == 0 else f'{size:.2f} {sym}'

    size /= 1024

  return f'{size * 1024:.2f} {syms[-1]}'

maybe_call(obj, name, *args, **kwargs)

Calls a method on an object if it exists and is callable.

Parameters:

Name Type Description Default
obj

The object to call the method on.

required
name

The method name.

required
*args

Positional arguments for the method.

()
**kwargs

Keyword arguments for the method.

{}

Returns:

Type Description

The result of the method call, or None if the method does not exist

or is not callable.

Source code in py_misc_utils/core_utils.py
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def maybe_call(obj, name, *args, **kwargs):
  """Calls a method on an object if it exists and is callable.

  Args:
    obj: The object to call the method on.
    name: The method name.
    *args: Positional arguments for the method.
    **kwargs: Keyword arguments for the method.

  Returns:
    The result of the method call, or None if the method does not exist
    or is not callable.
  """
  fn = getattr(obj, name, None)

  return fn(*args, **kwargs) if callable(fn) else None

maybe_call_dv(obj, name, defval, *args, **kwargs)

Calls a method on an object if it exists and is callable, with a default.

Parameters:

Name Type Description Default
obj

The object to call the method on.

required
name

The method name.

required
defval

The default value returned if the method is missing or not callable.

required
*args

Positional arguments for the method.

()
**kwargs

Keyword arguments for the method.

{}

Returns:

Type Description

The result of the method call, or defval if the method is not available.

Source code in py_misc_utils/core_utils.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
def maybe_call_dv(obj, name, defval, *args, **kwargs):
  """Calls a method on an object if it exists and is callable, with a default.

  Args:
    obj: The object to call the method on.
    name: The method name.
    defval: The default value returned if the method is missing or not callable.
    *args: Positional arguments for the method.
    **kwargs: Keyword arguments for the method.

  Returns:
    The result of the method call, or ``defval`` if the method is not available.
  """
  fn = getattr(obj, name, None)

  return fn(*args, **kwargs) if callable(fn) else defval

unique(data)

Groups indices of equal values in a sequence.

Parameters:

Name Type Description Default
data

A sequence of hashable values.

required

Returns:

Type Description

A defaultdict mapping each unique value to an array.array of indices

where that value occurs.

Source code in py_misc_utils/core_utils.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def unique(data):
  """Groups indices of equal values in a sequence.

  Args:
    data: A sequence of hashable values.

  Returns:
    A defaultdict mapping each unique value to an array.array of indices
    where that value occurs.
  """
  udata = collections.defaultdict(lambda: array.array('L'))
  for i, v in enumerate(data):
    udata[v].append(i)

  return udata

enum_max(cls)

Returns the maximum value of an enum class.

Parameters:

Name Type Description Default
cls

An enum class (iterable of values).

required

Returns:

Type Description

The largest value in cls.

Source code in py_misc_utils/core_utils.py
627
628
629
630
631
632
633
634
635
636
def enum_max(cls):
  """Returns the maximum value of an enum class.

  Args:
    cls: An enum class (iterable of values).

  Returns:
    The largest value in ``cls``.
  """
  return max(x for x in cls)

enum_bits(cls)

Returns the number of bits needed to represent the max enum value.

Parameters:

Name Type Description Default
cls

An enum class.

required

Returns:

Type Description

The bit length of enum_max(cls).

Source code in py_misc_utils/core_utils.py
639
640
641
642
643
644
645
646
647
648
def enum_bits(cls):
  """Returns the number of bits needed to represent the max enum value.

  Args:
    cls: An enum class.

  Returns:
    The bit length of ``enum_max(cls)``.
  """
  return enum_max(cls).bit_length()

signature(v)

Computes a structural signature of a value for comparison purposes.

Parameters:

Name Type Description Default
v

A value (dict, list, tuple, or scalar).

required

Returns:

Type Description

A normalized representation: dicts become sorted dicts of signatures,

lists/tuples become typed sequences of signatures, scalars become their

type.

Source code in py_misc_utils/core_utils.py
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def signature(v):
  """Computes a structural signature of a value for comparison purposes.

  Args:
    v: A value (dict, list, tuple, or scalar).

  Returns:
    A normalized representation: dicts become sorted dicts of signatures,
    lists/tuples become typed sequences of signatures, scalars become their
    type.
  """
  if isdict(v):
    vdata = dict()
    for k in sorted(v.keys()):
      vdata[k] = signature(v[k])

    return vdata
  elif isinstance(v, (list, tuple)):
    vdata = [signature(e) for e in v]

    return type(v)(vdata)

  return type(v)

equal_signature(a, b, subcls=True)

Compares two structural signatures for equality.

Parameters:

Name Type Description Default
a

First signature/value to compare.

required
b

Second signature/value to compare.

required
subcls

If True, uses issubclass checks for scalars (allows subclass matches). If False, uses exact equality.

True

Returns:

Type Description

True if the signatures are structurally equal, False otherwise.

Source code in py_misc_utils/core_utils.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
def equal_signature(a, b, subcls=True):
  """Compares two structural signatures for equality.

  Args:
    a: First signature/value to compare.
    b: Second signature/value to compare.
    subcls: If True, uses issubclass checks for scalars (allows subclass
      matches). If False, uses exact equality.

  Returns:
    True if the signatures are structurally equal, False otherwise.
  """
  if isdict(a):
    if not isdict(b) or len(a) != len(b):
      return False

    for k, t in a.items():
      tb = b.get(k)
      if tb is None or not equal_signature(t, tb, subcls=subcls):
        return False

    return True
  elif isinstance(a, (list, tuple)):
    if type(a) != type(b) or len(a) != len(b):
      return False

    for ea, eb in zip(a, b):
      if not equal_signature(ea, eb, subcls=subcls):
        return False

    return True

  a = a if isinstance(a, type) else signature(a)
  b = b if isinstance(b, type) else signature(b)

  return issubclass(a, b) or issubclass(b, a) if subcls else a == b

genhash(v)

Computes a hash for nested data structures (dicts, lists, tuples, scalars).

Parameters:

Name Type Description Default
v

A value to hash (dict, list, tuple, or scalar).

required

Returns:

Type Description

An integer hash incorporating type and nested structure.

Source code in py_misc_utils/core_utils.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def genhash(v):
  """Computes a hash for nested data structures (dicts, lists, tuples, scalars).

  Args:
    v: A value to hash (dict, list, tuple, or scalar).

  Returns:
    An integer hash incorporating type and nested structure.
  """
  if isdict(v):
    vdata = []
    for k in sorted(v.keys()):
      vdata.append(genhash(k))
      vdata.append(genhash(v[k]))

    return hash((type(v), tuple(vdata)))
  elif isinstance(v, (list, tuple)):
    vdata = [genhash(e) for e in v]

    return hash((type(v), tuple(vdata)))

  return hash((type(v), v))

norm_slice(start, stop, size)

Normalizes slice start/stop indices, handling None and negative values.

Parameters:

Name Type Description Default
start

The start index (None or negative allowed).

required
stop

The stop index (None or negative allowed).

required
size

The sequence size used to resolve negative indices.

required

Returns:

Type Description

A tuple (start, stop) with normalized non-negative indices.

Source code in py_misc_utils/core_utils.py
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
def norm_slice(start, stop, size):
  """Normalizes slice start/stop indices, handling None and negative values.

  Args:
    start: The start index (None or negative allowed).
    stop: The stop index (None or negative allowed).
    size: The sequence size used to resolve negative indices.

  Returns:
    A tuple ``(start, stop)`` with normalized non-negative indices.
  """
  if start is None:
    start = 0
  elif start < 0:
    start = size + start
  if stop is None:
    stop = size
  elif stop < 0:
    stop = size + stop

  return start, stop

run_async(fn, *args, **kwargs)

Runs a function in a daemon thread and returns the thread object.

Parameters:

Name Type Description Default
fn

The callable to run asynchronously.

required
*args

Positional arguments for fn.

()
**kwargs

Keyword arguments for fn.

{}

Returns:

Type Description

The started threading.Thread instance (daemon=True).

Source code in py_misc_utils/core_utils.py
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
def run_async(fn, *args, **kwargs):
  """Runs a function in a daemon thread and returns the thread object.

  Args:
    fn: The callable to run asynchronously.
    *args: Positional arguments for fn.
    **kwargs: Keyword arguments for fn.

  Returns:
    The started ``threading.Thread`` instance (daemon=True).
  """
  thread = threading.Thread(target=fn, args=args, kwargs=kwargs, daemon=True)
  thread.start()

  return thread

bisect_right(x, key, hi, lo=0)

Binary search: returns rightmost insertion point for x in key-sorted range.

Parameters:

Name Type Description Default
x

The target value.

required
key

A function mapping index to comparable value.

required
hi

Upper bound (exclusive) of the search range.

required
lo

Lower bound (inclusive) of the search range (default 0).

0

Returns:

Type Description

The index where x would be inserted to maintain order (right side).

Source code in py_misc_utils/core_utils.py
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
def bisect_right(x, key, hi, lo=0):
  """Binary search: returns rightmost insertion point for x in key-sorted range.

  Args:
    x: The target value.
    key: A function mapping index to comparable value.
    hi: Upper bound (exclusive) of the search range.
    lo: Lower bound (inclusive) of the search range (default 0).

  Returns:
    The index where x would be inserted to maintain order (right side).
  """
  tas.check_ge(lo, 0)
  while lo < hi:
    mid = (lo + hi) // 2
    if x < key(mid):
      hi = mid
    else:
      lo = mid + 1

  return lo

bisect_left(x, key, hi, lo=0)

Binary search: returns leftmost insertion point for x in key-sorted range.

Parameters:

Name Type Description Default
x

The target value.

required
key

A function mapping index to comparable value.

required
hi

Upper bound (exclusive) of the search range.

required
lo

Lower bound (inclusive) of the search range (default 0).

0

Returns:

Type Description

The index where x would be inserted to maintain order (left side).

Source code in py_misc_utils/core_utils.py
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
def bisect_left(x, key, hi, lo=0):
  """Binary search: returns leftmost insertion point for x in key-sorted range.

  Args:
    x: The target value.
    key: A function mapping index to comparable value.
    hi: Upper bound (exclusive) of the search range.
    lo: Lower bound (inclusive) of the search range (default 0).

  Returns:
    The index where x would be inserted to maintain order (left side).
  """
  tas.check_ge(lo, 0)
  while lo < hi:
    mid = (lo + hi) // 2
    if key(mid) < x:
      lo = mid + 1
    else:
      hi = mid

  return lo

rewrited_exception(ex, msg)

Rewrites an exception message while preserving the original traceback.

Parameters:

Name Type Description Default
ex

The original exception instance.

required
msg

Additional message text to append.

required

Returns:

Type Description

A new exception of the same class with the combined message and original

traceback attached.

Source code in py_misc_utils/core_utils.py
824
825
826
827
828
829
830
831
832
833
834
835
836
837
def rewrited_exception(ex, msg):
  """Rewrites an exception message while preserving the original traceback.

  Args:
    ex: The original exception instance.
    msg: Additional message text to append.

  Returns:
    A new exception of the same class with the combined message and original
    traceback attached.
  """
  xmsg = f'{ex}{msg}'

  return ex.__class__(xmsg).with_traceback(ex.__traceback__)

obj_from_dict(cls, data)

Constructs an object of cls from a dictionary of attribute values.

Parameters:

Name Type Description Default
cls

The class to instantiate.

required
data

A dict mapping parameter names to values.

required

Returns:

Type Description

A new instance of cls constructed from data.

Source code in py_misc_utils/core_utils.py
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
def obj_from_dict(cls, data):
  """Constructs an object of cls from a dictionary of attribute values.

  Args:
    cls: The class to instantiate.
    data: A dict mapping parameter names to values.

  Returns:
    A new instance of ``cls`` constructed from ``data``.
  """
  args, kwargs = [], dict()
  slots = getattr(cls, '__slots__', None)
  if slots is not None:
    kwargs = {k: data.get(k) for k in slots}
  else:
    sig = inspect.signature(cls)

    for n, p in sig.parameters.items():
      if p.kind == p.POSITIONAL_ONLY:
        args.append(data.get(n))
      else:
        kwargs[n] = data.get(n)

  return cls(*args, **kwargs)

clone(obj)

Returns a shallow copy of an object, using its clone() method if available.

Parameters:

Name Type Description Default
obj

The object to clone.

required

Returns:

Type Description

A shallow copy of obj.

Source code in py_misc_utils/core_utils.py
866
867
868
869
870
871
872
873
874
875
876
877
def clone(obj):
  """Returns a shallow copy of an object, using its clone() method if available.

  Args:
    obj: The object to clone.

  Returns:
    A shallow copy of ``obj``.
  """
  clone_fn = getattr(obj, 'clone', None)

  return clone_fn() if callable(clone_fn) else copy.copy(obj)

is_namedtuple(obj)

Checks whether an object is a named tuple.

Parameters:

Name Type Description Default
obj

The object to check.

required

Returns:

Type Description

True if obj is a tuple with _asdict and _fields attributes.

Source code in py_misc_utils/core_utils.py
880
881
882
883
884
885
886
887
888
889
def is_namedtuple(obj):
  """Checks whether an object is a named tuple.

  Args:
    obj: The object to check.

  Returns:
    True if obj is a tuple with _asdict and _fields attributes.
  """
  return isinstance(obj, tuple) and hasattr(obj, '_asdict') and hasattr(obj, '_fields')

new_with(obj, **kwargs)

Returns a copy of an object with specified attributes updated.

Parameters:

Name Type Description Default
obj

The object to copy and modify.

required
**kwargs

Attributes to set on the copy.

{}

Returns:

Type Description

A copy of obj with the given attributes updated. Named tuples use

_replace, dicts use update, other objects use setattr.

Source code in py_misc_utils/core_utils.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
def new_with(obj, **kwargs):
  """Returns a copy of an object with specified attributes updated.

  Args:
    obj: The object to copy and modify.
    **kwargs: Attributes to set on the copy.

  Returns:
    A copy of ``obj`` with the given attributes updated. Named tuples use
    ``_replace``, dicts use ``update``, other objects use setattr.
  """
  if is_namedtuple(obj):
    return obj._replace(**kwargs)

  nobj = copy.copy(obj)
  if isdict(nobj):
    nobj.update(kwargs)
  else:
    for k, v in kwargs.items():
      setattr(nobj, k, v)

  return nobj

make_ntuple(ntc, args)

Creates a named tuple instance from a dict of field values.

Parameters:

Name Type Description Default
ntc

The named tuple class.

required
args

A dict mapping field names to values. Missing fields use defaults.

required

Returns:

Type Description

A new instance of ntc.

Source code in py_misc_utils/core_utils.py
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
def make_ntuple(ntc, args):
  """Creates a named tuple instance from a dict of field values.

  Args:
    ntc: The named tuple class.
    args: A dict mapping field names to values. Missing fields use defaults.

  Returns:
    A new instance of ``ntc``.
  """
  targs = []
  for f in ntc._fields:
    fv = args.get(f, _NONE)
    if fv is _NONE:
      fv = ntc._field_defaults.get(f)

    targs.append(fv)

  return ntc._make(targs)

dict_add(ddict, name, value)

Adds a value to a dict, accumulating multiple values in a ValueList.

Parameters:

Name Type Description Default
ddict

The dictionary to modify.

required
name

The key under which to store the value.

required
value

The value to add. If the key already exists, the value is appended to a ValueList (creating one if needed).

required
Source code in py_misc_utils/core_utils.py
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def dict_add(ddict, name, value):
  """Adds a value to a dict, accumulating multiple values in a ValueList.

  Args:
    ddict: The dictionary to modify.
    name: The key under which to store the value.
    value: The value to add. If the key already exists, the value is appended
      to a ValueList (creating one if needed).
  """
  ivalue = ddict.get(name, _NONE)
  if ivalue is not _NONE:
    if isinstance(ivalue, ValueList):
      ivalue.append(value)
    else:
      ddict[name] = ValueList((ivalue, value))
  else:
    ddict[name] = value

dict_update_append(d, **kwargs)

Updates a dict with multiple values, accumulating via dict_add.

Parameters:

Name Type Description Default
d

The dictionary to update.

required
**kwargs

Key-value pairs to add using dict_add semantics.

{}
Source code in py_misc_utils/core_utils.py
 994
 995
 996
 997
 998
 999
1000
1001
1002
def dict_update_append(d, **kwargs):
  """Updates a dict with multiple values, accumulating via dict_add.

  Args:
    d: The dictionary to update.
    **kwargs: Key-value pairs to add using dict_add semantics.
  """
  for k, v in kwargs.items():
    dict_add(d, k, v)

enum_dict_values(ddict, name)

Yields all values associated with a key, including accumulated ValueList entries.

Parameters:

Name Type Description Default
ddict

The dictionary to search.

required
name

The key whose values should be enumerated.

required

Yields:

Type Description

Each value stored under name. If the value is a ValueList, yields

each element; otherwise yields the single value.

Source code in py_misc_utils/core_utils.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
def enum_dict_values(ddict, name):
  """Yields all values associated with a key, including accumulated ValueList entries.

  Args:
    ddict: The dictionary to search.
    name: The key whose values should be enumerated.

  Yields:
    Each value stored under ``name``. If the value is a ValueList, yields
    each element; otherwise yields the single value.
  """
  ivalue = ddict.get(name, _NONE)
  if ivalue is not _NONE:
    if isinstance(ivalue, ValueList):
      yield from ivalue
    else:
      yield ivalue

enum_unique(data, skip=None)

Yields unique elements from an iterable, optionally skipping a set.

Parameters:

Name Type Description Default
data

An iterable of hashable items.

required
skip

An optional iterable of items to skip (default empty).

None

Yields:

Type Description

Each unique item from data that is not in the skip set.

Source code in py_misc_utils/core_utils.py
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
def enum_unique(data, skip=None):
  """Yields unique elements from an iterable, optionally skipping a set.

  Args:
    data: An iterable of hashable items.
    skip: An optional iterable of items to skip (default empty).

  Yields:
    Each unique item from ``data`` that is not in the skip set.
  """
  uskip = set(skip or ())
  for x in data:
    if x not in uskip:
      uskip.add(x)
      yield x

get_property(obj, name, defval=None)

Gets an attribute from an object, calling it if it is callable.

Parameters:

Name Type Description Default
obj

The object to query.

required
name

The attribute name.

required
defval

Default value returned if the attribute is missing (default None).

None

Returns:

Type Description

The attribute value (called if callable), or defval if missing.

Source code in py_misc_utils/core_utils.py
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
def get_property(obj, name, defval=None):
  """Gets an attribute from an object, calling it if it is callable.

  Args:
    obj: The object to query.
    name: The attribute name.
    defval: Default value returned if the attribute is missing (default None).

  Returns:
    The attribute value (called if callable), or ``defval`` if missing.
  """
  p = getattr(obj, name, _NONE)
  if p is _NONE:
    return defval

  return p() if callable(p) else p

data_rewrite(v, rwfn)

Recursively rewrites a data structure using a rewrite function.

Parameters:

Name Type Description Default
v

The value to rewrite (scalar, list, tuple, dict, or object with dict).

required
rwfn

A function taking a value and returning a replacement, or None to keep the original.

required

Returns:

Type Description

The rewritten structure with the same types as the input. If no changes

were made, the original object is returned unchanged.

Source code in py_misc_utils/core_utils.py
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
def data_rewrite(v, rwfn):
  """Recursively rewrites a data structure using a rewrite function.

  Args:
    v: The value to rewrite (scalar, list, tuple, dict, or object with __dict__).
    rwfn: A function taking a value and returning a replacement, or None to
      keep the original.

  Returns:
    The rewritten structure with the same types as the input. If no changes
    were made, the original object is returned unchanged.
  """
  rwv = rwfn(v)
  if rwv is not None:
    return rwv
  elif isinstance(v, (list, tuple)):
    new_values, rewritten = [], False
    for x in v:
      new_obj = data_rewrite(x, rwfn)
      new_values.append(new_obj)
      rewritten = rewritten or new_obj is not x

    return type(v)(new_values) if rewritten else v
  elif isdict(v):
    new_values, rewritten = [], False
    for k, x in v.items():
      new_k = data_rewrite(k, rwfn)
      new_x = data_rewrite(x, rwfn)
      new_values.append((new_k, new_x))
      rewritten = rewritten or new_k is not k or new_x is not x

    return type(v)(new_values) if rewritten else v
  elif hasattr(v, '__dict__'):
    new_values, rewritten = [], False
    for k, x in v.__dict__.items():
      new_k = data_rewrite(k, rwfn)
      new_x = data_rewrite(x, rwfn)
      new_values.append((new_k, new_x))
      rewritten = rewritten or new_k is not k or new_x is not x

    if rewritten:
      new_obj = copy.copy(v)
      new_obj.__dict__.update(**dict(new_values))

      return new_obj

    return v
  else:
    return v

recurse_apply(obj, name, fn)

Recursively applies a function to all elements of a nested structure.

Parameters:

Name Type Description Default
obj

The object to traverse (list, tuple, dict, or object with dict).

required
name

A path string used to identify the current element (for fn context).

required
fn

A callable taking (obj, name) and returning True to stop recursion at this node, or False to continue into children.

required
Source code in py_misc_utils/core_utils.py
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
def recurse_apply(obj, name, fn):
  """Recursively applies a function to all elements of a nested structure.

  Args:
    obj: The object to traverse (list, tuple, dict, or object with __dict__).
    name: A path string used to identify the current element (for fn context).
    fn: A callable taking (obj, name) and returning True to stop recursion
      at this node, or False to continue into children.
  """
  if not fn(obj, name):
    if isinstance(obj, (list, tuple)):
      for i, v in enumerate(obj):
        recurse_apply(v, f'{name}[{i}]', fn)
    elif isdict(obj):
      for k, v in obj.items():
        recurse_apply(v, f'{name}.{k}', fn)
    elif hasattr(obj, '__dict__'):
      for k, v in obj.__dict__.items():
        recurse_apply(v, f'{name}.{k}', fn)

compute_shape(data)

Computes the shape of a nested data structure.

Parameters:

Name Type Description Default
data

A nested list/tuple/object with an optional shape attribute.

required

Returns:

Type Description

A tuple of dimension lengths. If data has a shape property, that is

returned directly; otherwise the shape is computed by recursing into

the first element.

Source code in py_misc_utils/core_utils.py
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
def compute_shape(data):
  """Computes the shape of a nested data structure.

  Args:
    data: A nested list/tuple/object with an optional ``shape`` attribute.

  Returns:
    A tuple of dimension lengths. If data has a ``shape`` property, that is
    returned directly; otherwise the shape is computed by recursing into
    the first element.
  """
  sp = get_property(data, 'shape')
  if sp is not None:
    return tuple(sp)
  shape = []
  if hasattr(data, '__len__'):
    shape.append(len(data))
    if shape[0] > 0 and hasattr(data, '__getitem__'):
      shape.extend(compute_shape(data[0]))

  return tuple(shape)