Skip to content

utils

Utility functions for common operations.

This module provides a collection of general-purpose utility functions including: - String formatting and manipulation - Dictionary and data structure operations - Configuration file handling (YAML) - Environment variable parsing - Object creation and inspection - Code compilation and execution helpers - Shape and array utilities - State persistence

pickle_proto()

Get the pickle protocol version from environment or use highest.

Returns:

Name Type Description
int

Pickle protocol version (default: pickle.HIGHEST_PROTOCOL).

Source code in py_misc_utils/utils.py
50
51
52
53
54
55
56
def pickle_proto():
  """Get the pickle protocol version from environment or use highest.

  Returns:
    int: Pickle protocol version (default: pickle.HIGHEST_PROTOCOL).
  """
  return getenv('PICKLE_PROTO', dtype=int, defval=pickle.HIGHEST_PROTOCOL)

fname()

Get the name of the calling function.

Returns:

Name Type Description
str

Name of the function that called this function.

Source code in py_misc_utils/utils.py
59
60
61
62
63
64
65
def fname():
  """Get the name of the calling function.

  Returns:
    str: Name of the function that called this function.
  """
  return tb.get_frame(1).f_code.co_name

stri(l, float_fmt=None, dict_expand=False)

Convert an object to a detailed string representation.

Parameters:

Name Type Description Default
l

Object to convert to string.

required
float_fmt

Format string for floating point numbers (default: '.3e').

None
dict_expand

Whether to expand object dict attributes (default: False).

False

Returns:

Name Type Description
str

Detailed string representation of the object.

Source code in py_misc_utils/utils.py
116
117
118
119
120
121
122
123
124
125
126
127
def stri(l, float_fmt=None, dict_expand=False):
  """Convert an object to a detailed string representation.

  Args:
    l: Object to convert to string.
    float_fmt: Format string for floating point numbers (default: '.3e').
    dict_expand: Whether to expand object __dict__ attributes (default: False).

  Returns:
    str: Detailed string representation of the object.
  """
  return _stri(l, dict(), float_fmt or '.3e', dict_expand)

repr_fmt(obj, *fields, repr_none=False, sep=', ')

Format an object's attributes into a string representation.

Parameters:

Name Type Description Default
obj

Object whose attributes to format.

required
*fields

Attribute names to include. Can use '!attr' to force inclusion even if None, or 'attr=name' to use a custom display name.

()
repr_none

Whether to include attributes that are None (default: False).

False
sep

Separator between fields (default: ', ').

', '

Returns:

Name Type Description
str

Formatted string representation.

Source code in py_misc_utils/utils.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def repr_fmt(obj, *fields, repr_none=False, sep=', '):
  """Format an object's attributes into a string representation.

  Args:
    obj: Object whose attributes to format.
    *fields: Attribute names to include. Can use '!attr' to force inclusion
      even if None, or 'attr=name' to use a custom display name.
    repr_none: Whether to include attributes that are None (default: False).
    sep: Separator between fields (default: ', ').

  Returns:
    str: Formatted string representation.
  """
  parts = []
  for fname in expand_strings(*fields):
    rnone, xname = repr_none, fname

    m = re.match(r'([!])?(\w+)\s*(=\s*(\w*))?', fname)
    if m:
      fname = m.group(2)
      rnone = m.group(1) == '!'
      xname = m.group(4)
      if xname is None:
        xname = fname

    data = getattr(obj, fname, None)
    if data is not None or rnone:
      parts.append(f'{xname}={data}' if xname else str(data))

  return sep.join(parts)

mget(d, *args, as_dict=False)

Get multiple keys from a dictionary.

Parameters:

Name Type Description Default
d

Dictionary to query.

required
*args

Keys to retrieve (can be comma-separated strings).

()
as_dict

Return as dictionary instead of tuple (default: False).

False

Returns:

Type Description

Tuple of values or dictionary mapping keys to values.

Source code in py_misc_utils/utils.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def mget(d, *args, as_dict=False):
  """Get multiple keys from a dictionary.

  Args:
    d: Dictionary to query.
    *args: Keys to retrieve (can be comma-separated strings).
    as_dict: Return as dictionary instead of tuple (default: False).

  Returns:
    Tuple of values or dictionary mapping keys to values.
  """
  margs = expand_strings(*args)
  if as_dict:
    return {f: d.get(f) for f in margs}
  else:
    return tuple(d.get(f) for f in margs)

getvar(obj, name, defval=None)

Get an attribute or dictionary key with default.

Parameters:

Name Type Description Default
obj

A dictionary or an object supporting attribute access.

required
name

Key or attribute name to retrieve.

required
defval

Value returned when name is missing (default: None).

None

Returns:

Type Description

The value of the key or attribute, or defval.

Source code in py_misc_utils/utils.py
180
181
182
183
184
185
186
187
188
189
190
191
def getvar(obj, name, defval=None):
  """Get an attribute or dictionary key with default.

  Args:
    obj: A dictionary or an object supporting attribute access.
    name: Key or attribute name to retrieve.
    defval: Value returned when name is missing (default: None).

  Returns:
    The value of the key or attribute, or defval.
  """
  return obj.get(name, defval) if cu.isdict(obj) else getattr(obj, name, defval)

dict_subset(d, *keys)

Build a new dictionary holding only the specified keys.

Parameters:

Name Type Description Default
d

Dictionary to extract the keys from.

required
*keys

Keys to extract; comma-separated strings are expanded.

()

Returns:

Type Description

A new dictionary with the key/value pairs present in d.

Source code in py_misc_utils/utils.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def dict_subset(d, *keys):
  """Build a new dictionary holding only the specified keys.

  Args:
    d: Dictionary to extract the keys from.
    *keys: Keys to extract; comma-separated strings are expanded.

  Returns:
    A new dictionary with the key/value pairs present in d.
  """
  mkeys = expand_strings(*keys)
  subd = dict()
  for k in mkeys:
    v = d.get(k, _NONE)
    if v is not _NONE:
      subd[k] = v

  return subd

dict_setmissing(d, **kwargs)

Fill a dictionary with entries whose keys are still missing.

Parameters:

Name Type Description Default
d

Dictionary to add the missing entries to.

required
**kwargs

Candidate key/value pairs, used only when the key is not already present in d.

{}

Returns:

Type Description

The d dictionary updated in place.

Source code in py_misc_utils/utils.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def dict_setmissing(d, **kwargs):
  """Fill a dictionary with entries whose keys are still missing.

  Args:
    d: Dictionary to add the missing entries to.
    **kwargs: Candidate key/value pairs, used only when the key is not
      already present in d.

  Returns:
    The d dictionary updated in place.
  """
  kwargs.update(d)

  return kwargs

pop_kwargs(kwargs, names, args_key=None)

Pop arguments from a kwargs dictionary, with an extra-arguments sidecar.

Parameters:

Name Type Description Default
kwargs

Dictionary to pop the values from.

required
names

Names of the arguments to retrieve; comma-separated strings are expanded.

required
args_key

Name of an optional sidecar dictionary holding per-name values; when present it takes precedence over kwargs.

None

Returns:

Type Description

A tuple with the retrieved values, None for the missing ones.

Source code in py_misc_utils/utils.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def pop_kwargs(kwargs, names, args_key=None):
  """Pop arguments from a kwargs dictionary, with an extra-arguments sidecar.

  Args:
    kwargs: Dictionary to pop the values from.
    names: Names of the arguments to retrieve; comma-separated strings
      are expanded.
    args_key: Name of an optional sidecar dictionary holding per-name
      values; when present it takes precedence over kwargs.

  Returns:
    A tuple with the retrieved values, None for the missing ones.
  """
  xargs = kwargs.pop(args_key or '_', None)
  if xargs is not None:
    args = [xargs.get(name) for name in expand_strings(names)]
  else:
    args = [kwargs.pop(name, None) for name in expand_strings(names)]

  return tuple(args)

resplit(csstr, sep, unescape=False)

Split a string on a separator, trimming surrounding whitespace.

Parameters:

Name Type Description Default
csstr

String to split.

required
sep

Separator, treated as a regular expression.

required
unescape

If True, remove escape characters from the parts.

False

Returns:

Type Description

A tuple of the parts of the string. Empty parts between separators

are preserved.

Source code in py_misc_utils/utils.py
252
253
254
255
256
257
258
259
260
261
262
263
264
def resplit(csstr, sep, unescape=False):
  """Split a string on a separator, trimming surrounding whitespace.

  Args:
    csstr: String to split.
    sep: Separator, treated as a regular expression.
    unescape: If True, remove escape characters from the parts.

  Returns:
    A tuple of the parts of the string. Empty parts between separators
    are preserved.
  """
  return sp.split(csstr, r'\s*' + sep + r'\s*', unescape=unescape)

comma_split(csstr, unescape=False)

Split a string on commas, trimming surrounding whitespace.

Parameters:

Name Type Description Default
csstr

String to split.

required
unescape

If True, remove escape characters from the parts.

False

Returns:

Type Description

A tuple of the parts of the string. Empty parts between separators

are preserved.

Source code in py_misc_utils/utils.py
267
268
269
270
271
272
273
274
275
276
277
278
def comma_split(csstr, unescape=False):
  """Split a string on commas, trimming surrounding whitespace.

  Args:
    csstr: String to split.
    unescape: If True, remove escape characters from the parts.

  Returns:
    A tuple of the parts of the string. Empty parts between separators
    are preserved.
  """
  return sp.split(csstr, r'\s*,\s*', unescape=unescape)

ws_split(data, unescape=False)

Split a string on whitespace.

Parameters:

Name Type Description Default
data

String to split.

required
unescape

If True, remove escape characters from the parts.

False

Returns:

Type Description

A tuple of the parts of the string. Empty parts between separators

are preserved.

Source code in py_misc_utils/utils.py
281
282
283
284
285
286
287
288
289
290
291
292
def ws_split(data, unescape=False):
  """Split a string on whitespace.

  Args:
    data: String to split.
    unescape: If True, remove escape characters from the parts.

  Returns:
    A tuple of the parts of the string. Empty parts between separators
    are preserved.
  """
  return sp.split(data, r'\s+', unescape=unescape)

expand_strings(*args)

Expand comma-separated strings and sequences into a flat tuple of strings.

Parameters:

Name Type Description Default
*args

Strings or sequences. Strings are split by commas, sequences are flattened. Whitespace is stripped.

()

Returns:

Type Description

Tuple of non-empty strings.

Source code in py_misc_utils/utils.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def expand_strings(*args):
  """Expand comma-separated strings and sequences into a flat tuple of strings.

  Args:
    *args: Strings or sequences. Strings are split by commas, sequences are
      flattened. Whitespace is stripped.

  Returns:
    Tuple of non-empty strings.
  """
  margs = []
  for arg in args:
    if cu.is_sequence(arg):
      margs.extend(arg)
    else:
      margs.extend(comma_split(arg))

  return tuple(margs)

name_values(base_name, values)

Create named value pairs from a base name and values.

Parameters:

Name Type Description Default
base_name

Base name for the values.

required
values

Single value or sequence of values.

required

Returns:

Type Description

Tuple of (name, value) pairs. If multiple values, names are

'base_name.0', 'base_name.1', etc.

Source code in py_misc_utils/utils.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def name_values(base_name, values):
  """Create named value pairs from a base name and values.

  Args:
    base_name: Base name for the values.
    values: Single value or sequence of values.

  Returns:
    Tuple of (name, value) pairs. If multiple values, names are
    'base_name.0', 'base_name.1', etc.
  """
  names = []
  if isinstance(values, (list, tuple)):
    if len(values) == 1:
      names.append((base_name, values[0]))
    else:
      for i, v in enumerate(values):
        names.append((f'{base_name}.{i}', v))
  else:
    names.append((base_name, values))

  return tuple(names)

write_config(cfg, dest, **kwargs)

Write a configuration dictionary to a YAML file atomically.

Parameters:

Name Type Description Default
cfg

Configuration dictionary to write.

required
dest

Destination file path.

required
**kwargs

Additional arguments passed to yaml.dump().

{}
Source code in py_misc_utils/utils.py
339
340
341
342
343
344
345
346
347
348
349
350
def write_config(cfg, dest, **kwargs):
  """Write a configuration dictionary to a YAML file atomically.

  Args:
    cfg: Configuration dictionary to write.
    dest: Destination file path.
    **kwargs: Additional arguments passed to yaml.dump().
  """
  default_flow_style = kwargs.get('default_flow_style', False)

  with fow.FileOverwrite(dest, mode='wt') as df:
    yaml.dump(cfg, df, default_flow_style=default_flow_style, **kwargs)

config_to_string(cfg, **kwargs)

Convert a configuration dictionary to a YAML string.

Parameters:

Name Type Description Default
cfg

Configuration dictionary.

required
**kwargs

Additional arguments passed to yaml.dump().

{}

Returns:

Name Type Description
str

YAML representation of the configuration.

Source code in py_misc_utils/utils.py
353
354
355
356
357
358
359
360
361
362
363
364
365
def config_to_string(cfg, **kwargs):
  """Convert a configuration dictionary to a YAML string.

  Args:
    cfg: Configuration dictionary.
    **kwargs: Additional arguments passed to yaml.dump().

  Returns:
    str: YAML representation of the configuration.
  """
  default_flow_style = kwargs.get('default_flow_style', False)

  return yaml.dump(cfg, default_flow_style=default_flow_style, **kwargs)

parse_config(cfg)

Parse a configuration from YAML string or file.

Parameters:

Name Type Description Default
cfg

YAML string, or path to a YAML file (detected by not starting with [ or {).

required

Returns:

Type Description

Parsed configuration dictionary.

Source code in py_misc_utils/utils.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
def parse_config(cfg):
  """Parse a configuration from YAML string or file.

  Args:
    cfg: YAML string, or path to a YAML file (detected by not starting with [ or {).

  Returns:
    Parsed configuration dictionary.
  """
  if not re.match(r'[\[\{]', cfg):
    # It must be either a dictionary in YAML format, or a valid path.
    with gfs.open(cfg, mode='r') as fd:
      data = fd.read()
  else:
    data = cfg

  return yaml.safe_load(data)

load_config(path, extra=None)

Load configuration from a path, optionally merging extra key-value pairs.

Parameters:

Name Type Description Default
path

Path to configuration file or YAML string.

required
extra

Optional dictionary of extra key-value pairs to merge into config.

None

Returns:

Type Description

Parsed configuration dictionary with extra keys merged.

Source code in py_misc_utils/utils.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def load_config(path, extra=None):
  """Load configuration from a path, optionally merging extra key-value pairs.

  Args:
    path: Path to configuration file or YAML string.
    extra: Optional dictionary of extra key-value pairs to merge into config.

  Returns:
    Parsed configuration dictionary with extra keys merged.
  """
  cfgd = parse_config(path)

  if extra:
    for k, v in extra.items():
      if v is not None:
        cfgd[k] = v

  return cfgd

fatal(msg, exc=RuntimeError)

Raise an exception with a formatted message.

Parameters:

Name Type Description Default
msg

Error message.

required
exc

Exception class to raise (default: RuntimeError).

RuntimeError

Raises:

Type Description
exc

The specified exception with the given message.

Source code in py_misc_utils/utils.py
407
408
409
410
411
412
413
414
415
416
417
def fatal(msg, exc=RuntimeError):
  """Raise an exception with a formatted message.

  Args:
    msg: Error message.
    exc: Exception class to raise (default: RuntimeError).

  Raises:
    exc: The specified exception with the given message.
  """
  alog.xraise(exc, msg, stacklevel=2)

assert_instance(msg, t, ta)

Assert that an object is an instance of a type (or one of several types).

Parameters:

Name Type Description Default
msg

Error message prefix.

required
t

Object to check.

required
ta

Type or tuple of types to check against.

required

Raises:

Type Description
ValueError

If t is not an instance of ta.

Source code in py_misc_utils/utils.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def assert_instance(msg, t, ta):
  """Assert that an object is an instance of a type (or one of several types).

  Args:
    msg: Error message prefix.
    t: Object to check.
    ta: Type or tuple of types to check against.

  Raises:
    ValueError: If t is not an instance of ta.
  """
  if not isinstance(t, ta):
    parts = [msg, f': {iu.cname(t)} is not ']
    if isinstance(ta, (list, tuple)):
      parts.append('one of (')
      parts.append(', '.join(iu.cname(x) for x in ta))
      parts.append(')')
    else:
      parts.append(f'a {iu.cname(ta)}')

    alog.xraise(ValueError, ''.join(parts))

make_object(**kwargs)

Create a simple object with attributes from keyword arguments.

Parameters:

Name Type Description Default
**kwargs

Attributes to set on the object.

{}

Returns:

Name Type Description
Obj

A simple object with the given attributes.

Source code in py_misc_utils/utils.py
443
444
445
446
447
448
449
450
451
452
def make_object(**kwargs):
  """Create a simple object with attributes from keyword arguments.

  Args:
    **kwargs: Attributes to set on the object.

  Returns:
    Obj: A simple object with the given attributes.
  """
  return obj.Obj(**kwargs)

make_object_recursive(**kwargs)

Create a nested object structure from keyword arguments.

Parameters:

Name Type Description Default
**kwargs

Attributes to set. Dictionary values are recursively converted to objects.

{}

Returns:

Name Type Description
Obj

A nested object structure.

Source code in py_misc_utils/utils.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
def make_object_recursive(**kwargs):
  """Create a nested object structure from keyword arguments.

  Args:
    **kwargs: Attributes to set. Dictionary values are recursively converted
      to objects.

  Returns:
    Obj: A nested object structure.
  """
  for k, v in kwargs.items():
    if cu.isdict(v):
      kwargs[k] = make_object_recursive(**v)

  return make_object(**kwargs)

locals_capture(locs, exclude='self')

Capture local variables into an object, excluding specified names.

Parameters:

Name Type Description Default
locs

Dictionary of local variables (typically from locals()).

required
exclude

Comma-separated string or sequence of names to exclude (default: 'self').

'self'

Returns:

Name Type Description
Obj

Object with captured local variables as attributes.

Source code in py_misc_utils/utils.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def locals_capture(locs, exclude='self'):
  """Capture local variables into an object, excluding specified names.

  Args:
    locs: Dictionary of local variables (typically from locals()).
    exclude: Comma-separated string or sequence of names to exclude
      (default: 'self').

  Returns:
    Obj: Object with captured local variables as attributes.
  """
  exclude = set(expand_strings(exclude, 'self'))

  return make_object(**{k: v for k, v in locs.items() if k not in exclude})

sreplace(rex, data, mapfn, nmapfn=None, join=True)

Rewrite the parts of a string matching a regular expression.

The pattern must define a capture group: matched groups are passed to mapfn, while the unmatched text is passed to nmapfn.

Parameters:

Name Type Description Default
rex

Regular expression whose first group drives the replacement.

required
data

String to rewrite.

required
mapfn

Callable mapping a matched group to its replacement.

required
nmapfn

Optional callable mapping the non-matching text (default: identity).

None
join

If True, return the rewritten string; if False return the list of the rewritten parts.

True

Returns:

Type Description

The rewritten string, or the list of its parts when join is False.

Source code in py_misc_utils/utils.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def sreplace(rex, data, mapfn, nmapfn=None, join=True):
  """Rewrite the parts of a string matching a regular expression.

  The pattern must define a capture group: matched groups are passed to
  mapfn, while the unmatched text is passed to nmapfn.

  Args:
    rex: Regular expression whose first group drives the replacement.
    data: String to rewrite.
    mapfn: Callable mapping a matched group to its replacement.
    nmapfn: Optional callable mapping the non-matching text (default:
      identity).
    join: If True, return the rewritten string; if False return the list
      of the rewritten parts.

  Returns:
    The rewritten string, or the list of its parts when join is False.
  """
  nmapfn = nmapfn if nmapfn is not None else cu.ident

  lastpos, parts = 0, []
  for m in re.finditer(rex, data):
    start, end = m.span()
    if start > lastpos:
      parts.append(nmapfn(data[lastpos:start]))

    lastpos = end
    mid = mapfn(m.group(1))
    parts.append(mid)

  if lastpos < len(data):
    parts.append(nmapfn(data[lastpos:]))

  return ''.join(parts) if join else parts

as_sequence(v, t=tuple)

Convert a value into a sequence of the given type.

Single elements are wrapped into a one-element sequence, while sequences and generators are converted as-is.

Parameters:

Name Type Description Default
v

Value to convert.

required
t

Target sequence type, or a tuple of types tried in order when v already is a sequence (default: tuple).

tuple

Returns:

Type Description

The value as a sequence of type t.

Source code in py_misc_utils/utils.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def as_sequence(v, t=tuple):
  """Convert a value into a sequence of the given type.

  Single elements are wrapped into a one-element sequence, while
  sequences and generators are converted as-is.

  Args:
    v: Value to convert.
    t: Target sequence type, or a tuple of types tried in order when v
      already is a sequence (default: tuple).

  Returns:
    The value as a sequence of type t.
  """
  if isinstance(t, (list, tuple)):
    for st in t:
      if isinstance(v, st):
        return v

    return t[0]([v]) if not isinstance(v, types.GeneratorType) else t[0](v)

  if isinstance(v, t):
    return v

  return t(v) if cu.is_sequence(v) else t([v])

format(seq, fmt)

Format the elements of a sequence with a format spec.

Parameters:

Name Type Description Default
seq

Sequence of values to format.

required
fmt

Format specification, as per the format mini-language.

required

Returns:

Type Description

A sequence of the same type of seq with the formatted elements.

Source code in py_misc_utils/utils.py
551
552
553
554
555
556
557
558
559
560
561
562
563
def format(seq, fmt):
  """Format the elements of a sequence with a format spec.

  Args:
    seq: Sequence of values to format.
    fmt: Format specification, as per the format mini-language.

  Returns:
    A sequence of the same type of seq with the formatted elements.
  """
  sfmt = f'{{:{fmt}}}'

  return type(seq)(sfmt.format(x) for x in seq)

value_or(v, defval)

Return v, or defval when v is None.

Source code in py_misc_utils/utils.py
566
567
568
def value_or(v, defval):
  """Return v, or defval when v is None."""
  return v if v is not None else defval

dict_rget(sdict, path, defval=None, sep='/')

Get a value nested inside dictionaries using a path.

Parameters:

Name Type Description Default
sdict

Dictionary to query.

required
path

Slash-separated path of keys, or an already split sequence of keys.

required
defval

Value returned when the path cannot be resolved.

None
sep

Separator of the path components (default: '/').

'/'

Returns:

Type Description

The value at the path, or defval.

Source code in py_misc_utils/utils.py
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def dict_rget(sdict, path, defval=None, sep='/'):
  """Get a value nested inside dictionaries using a path.

  Args:
    sdict: Dictionary to query.
    path: Slash-separated path of keys, or an already split sequence of
      keys.
    defval: Value returned when the path cannot be resolved.
    sep: Separator of the path components (default: '/').

  Returns:
    The value at the path, or defval.
  """
  dpath = path.strip(sep).split(sep) if isinstance(path, str) else path

  result = sdict
  for key in dpath:
    if not cu.isdict(result):
      return defval

    result = result.get(key, defval)

  return result

dict_rset(sdict, path, value, sep='/', extend=False)

Set a value nested inside dictionaries using a path.

Missing intermediate dictionaries are created, and existing ones must be dictionaries.

Parameters:

Name Type Description Default
sdict

Dictionary to modify.

required
path

Slash-separated path of keys, or an already split sequence of keys.

required
value

Value to set at the path.

required
sep

Separator of the path components (default: '/').

'/'
extend

If True, extend the existing value with value instead of replacing it.

False

Raises:

Type Description
ValueError

When an intermediate entry is not a dictionary.

Source code in py_misc_utils/utils.py
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def dict_rset(sdict, path, value, sep='/', extend=False):
  """Set a value nested inside dictionaries using a path.

  Missing intermediate dictionaries are created, and existing ones must
  be dictionaries.

  Args:
    sdict: Dictionary to modify.
    path: Slash-separated path of keys, or an already split sequence of
      keys.
    value: Value to set at the path.
    sep: Separator of the path components (default: '/').
    extend: If True, extend the existing value with value instead of
      replacing it.

  Raises:
    ValueError: When an intermediate entry is not a dictionary.
  """
  dpath = path.strip(sep).split(sep) if isinstance(path, str) else path

  dest = sdict
  for skey in dpath[:-1]:
    subd = dest.get(skey)
    if subd is None:
      subd = dict()
      dest[skey] = subd
    else:
      tas.check(cu.isdict(subd), msg=f'Not a folder (dict): {skey} = {type(subd)}')

    dest = subd

  skey = dpath[-1]
  if not extend:
    dest[skey] = value
  else:
    xvalue = dest.get(skey)
    if xvalue is None:
      dest[skey] = value
    else:
      xvalue.extend(value)

make_index_dict(vals)

Build a value-to-index dictionary from a sequence of values.

Parameters:

Name Type Description Default
vals

Sequence of hashable values.

required

Returns:

Type Description

A dict mapping each value to its ordinal position in vals.

Source code in py_misc_utils/utils.py
638
639
640
641
642
643
644
645
646
647
def make_index_dict(vals):
  """Build a value-to-index dictionary from a sequence of values.

  Args:
    vals: Sequence of hashable values.

  Returns:
    A dict mapping each value to its ordinal position in vals.
  """
  return {v: i for i, v in enumerate(vals)}

append_index_dict(xlist, xdict, value)

Append a value to a list and record its index in a dict.

Parameters:

Name Type Description Default
xlist

List to append the value to.

required
xdict

Dict mapping values to list positions, updated in place.

required
value

Value to append.

required
Source code in py_misc_utils/utils.py
650
651
652
653
654
655
656
657
658
659
def append_index_dict(xlist, xdict, value):
  """Append a value to a list and record its index in a dict.

  Args:
    xlist: List to append the value to.
    xdict: Dict mapping values to list positions, updated in place.
    value: Value to append.
  """
  xlist.append(value)
  xdict[value] = len(xlist) - 1

compile(code, syms, env=None, vals=None, lookup_fn=None, delim=None)

Compile and execute code, extracting specified symbols.

Note that objects compiled with this API cannot be pickled. If that is a requirement, use the dynamod module.

Parameters:

Name Type Description Default
code

Source code string to compile and execute.

required
syms

Symbol names to extract from the executed code (comma-separated or sequence).

required
env

Execution environment dictionary (default: new dict).

None
vals

Values for template replacement in code (default: None).

None
lookup_fn

Function for template value lookup (default: None).

None
delim

Template delimiter (default: None).

None

Returns:

Type Description

Tuple of extracted symbol values in the order specified by syms.

Source code in py_misc_utils/utils.py
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
def compile(code, syms, env=None, vals=None, lookup_fn=None, delim=None):
  """Compile and execute code, extracting specified symbols.

  Note that objects compiled with this API cannot be pickled.
  If that is a requirement, use the dynamod module.

  Args:
    code: Source code string to compile and execute.
    syms: Symbol names to extract from the executed code (comma-separated or sequence).
    env: Execution environment dictionary (default: new dict).
    vals: Values for template replacement in code (default: None).
    lookup_fn: Function for template value lookup (default: None).
    delim: Template delimiter (default: None).

  Returns:
    Tuple of extracted symbol values in the order specified by syms.
  """
  # Note that objects compiled with this API cannot be pickled.
  # If that is a requirement, use the dynamod module.
  env = value_or(env, dict())
  if vals is not None or lookup_fn is not None:
    code = tr.template_replace(code, vals=vals, lookup_fn=lookup_fn, delim=delim)

  exec(code, env)  # noqa: S102 -- deliberate dynamic-code API

  return tuple(env.get(s) for s in expand_strings(syms))

run(path, fnname, *args, **kwargs)

Run a function from a Python file.

Parameters:

Name Type Description Default
path

Path to the Python file.

required
fnname

Name of the function to run.

required
*args

Positional arguments to pass to the function.

()
**kwargs

Keyword arguments. Supports 'compile_args' for compilation options.

{}

Returns:

Type Description

The return value of the called function.

Source code in py_misc_utils/utils.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
def run(path, fnname, *args, **kwargs):
  """Run a function from a Python file.

  Args:
    path: Path to the Python file.
    fnname: Name of the function to run.
    *args: Positional arguments to pass to the function.
    **kwargs: Keyword arguments. Supports 'compile_args' for compilation options.

  Returns:
    The return value of the called function.
  """
  compile_args, = pop_kwargs(kwargs, 'compile_args')

  fn, = compile(mm.file_view(path), fnname, **(compile_args or dict()))

  return fn(*args, **kwargs)

unpack_n(l, n, defval=None)

Unpack a sequence into exactly n elements.

Parameters:

Name Type Description Default
l

Sequence to unpack; single values are treated as one-element sequences.

required
n

Number of elements to return.

required
defval

Value used to pad the result when l has less than n elements.

None

Returns:

Type Description

A tuple with the first n elements of l, padded with defval.

Source code in py_misc_utils/utils.py
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def unpack_n(l, n, defval=None):
  """Unpack a sequence into exactly n elements.

  Args:
    l: Sequence to unpack; single values are treated as one-element
      sequences.
    n: Number of elements to return.
    defval: Value used to pad the result when l has less than n elements.

  Returns:
    A tuple with the first n elements of l, padded with defval.
  """
  l = as_sequence(l)

  return tuple(l[:n] if len(l) >= n else l + [defval] * (n - len(l)))

getenv(name, dtype=None, defval=None)

Get an environment variable with type conversion.

Parameters:

Name Type Description Default
name

Environment variable name.

required
dtype

Type to convert the value to (default: None, returns string).

None
defval

Default value if not set. Can be a callable for lazy evaluation.

None

Returns:

Type Description

The environment variable value converted to dtype, or default value.

Source code in py_misc_utils/utils.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def getenv(name, dtype=None, defval=None):
  """Get an environment variable with type conversion.

  Args:
    name: Environment variable name.
    dtype: Type to convert the value to (default: None, returns string).
    defval: Default value if not set. Can be a callable for lazy evaluation.

  Returns:
    The environment variable value converted to dtype, or default value.
  """
  # os.getenv expects the default value to be a string, so cannot be passed in there.
  env = os.getenv(name)
  if env is None:
    env = defval() if callable(defval) else defval
  if env is not None:
    return cu.to_type(env, dtype) if dtype is not None else env

env(name, defval, vtype=None)

Get an environment variable with a mandatory default value.

Parameters:

Name Type Description Default
name

Environment variable name.

required
defval

Default value returned when the variable is not set.

required
vtype

Type to convert the value to.

None

Returns:

Type Description

The environment variable value converted to vtype, or defval.

Source code in py_misc_utils/utils.py
745
746
747
748
749
750
751
752
753
754
755
756
def env(name, defval, vtype=None):
  """Get an environment variable with a mandatory default value.

  Args:
    name: Environment variable name.
    defval: Default value returned when the variable is not set.
    vtype: Type to convert the value to.

  Returns:
    The environment variable value converted to vtype, or defval.
  """
  return getenv(name, dtype=vtype, defval=defval)

envs(*args, as_dict=False)

Get multiple environment variables.

Parameters:

Name Type Description Default
*args

Variable names; comma-separated strings are expanded.

()
as_dict

If True, return a dict instead of a tuple (default: False).

False

Returns:

Type Description

A tuple or dict with the values of the variables, None when missing.

Source code in py_misc_utils/utils.py
759
760
761
762
763
764
765
766
767
768
769
def envs(*args, as_dict=False):
  """Get multiple environment variables.

  Args:
    *args: Variable names; comma-separated strings are expanded.
    as_dict: If True, return a dict instead of a tuple (default: False).

  Returns:
    A tuple or dict with the values of the variables, None when missing.
  """
  return mget(os.environ, *args, as_dict=as_dict)

import_env(dest, *args)

Import environment variables into a dictionary, inferring value types.

Parameters:

Name Type Description Default
dest

Dictionary to add the variables to.

required
*args

Variable names; comma-separated strings are expanded.

()

Returns:

Type Description

The dest dictionary updated in place.

Source code in py_misc_utils/utils.py
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def import_env(dest, *args):
  """Import environment variables into a dictionary, inferring value types.

  Args:
    dest: Dictionary to add the variables to.
    *args: Variable names; comma-separated strings are expanded.

  Returns:
    The dest dictionary updated in place.
  """
  ivars = envs(*args, as_dict=True)
  for k, v in ivars.items():
    dest[k] = cu.infer_value(v)

  return dest

map_env(g, prefix='')

Override dictionary values from environment variables.

For every key of g, the PREFIXkey environment variable overrides the corresponding value when set, converting it to the type of the current value.

Parameters:

Name Type Description Default
g

Dictionary to update in place.

required
prefix

Prefix of the environment variable names (default: '').

''

Returns:

Type Description

The g dictionary updated in place.

Source code in py_misc_utils/utils.py
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
def map_env(g, prefix=''):
  """Override dictionary values from environment variables.

  For every key of g, the PREFIXkey environment variable overrides the
  corresponding value when set, converting it to the type of the current
  value.

  Args:
    g: Dictionary to update in place.
    prefix: Prefix of the environment variable names (default: '').

  Returns:
    The g dictionary updated in place.
  """
  ovr = dict()
  for k, v in g.items():
    ev = getenv(f'{prefix}{k}', dtype=type(v))
    if ev is not None:
      ovr[k] = ev

  g.update(ovr)

  return g

squeeze(shape, keep_dims=0, sdir=MAJOR)

Remove dimensions of size 1 from a shape.

Parameters:

Name Type Description Default
shape

Input shape as a sequence.

required
keep_dims

Minimum number of dimensions to keep (default: 0).

0
sdir

Direction to squeeze - MAJOR (leading) or MINOR (trailing) (default: MAJOR).

MAJOR

Returns:

Type Description

Shape with leading or trailing 1-dimensions removed, preserving type.

Raises:

Type Description
ValueError

If sdir is not MAJOR or MINOR.

Source code in py_misc_utils/utils.py
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
def squeeze(shape, keep_dims=0, sdir=MAJOR):
  """Remove dimensions of size 1 from a shape.

  Args:
    shape: Input shape as a sequence.
    keep_dims: Minimum number of dimensions to keep (default: 0).
    sdir: Direction to squeeze - MAJOR (leading) or MINOR (trailing) (default: MAJOR).

  Returns:
    Shape with leading or trailing 1-dimensions removed, preserving type.

  Raises:
    ValueError: If sdir is not MAJOR or MINOR.
  """
  sshape = list(shape)
  if sdir == MAJOR:
    while len(sshape) > keep_dims and sshape[0] == 1:
      sshape = sshape[1:]
  elif sdir == MINOR:
    while len(sshape) > keep_dims and sshape[-1] == 1:
      sshape = sshape[:-1]
  else:
    alog.xraise(ValueError, f'Unknown squeeze direction: {sdir}')

  return type(shape)(sshape)

flat2shape(data, shape)

Reshape flat data into a nested list structure matching the given shape.

Parameters:

Name Type Description Default
data

Flat sequence of data elements.

required
shape

Target shape as a sequence of dimensions.

required

Returns:

Type Description

Nested list structure matching the shape.

Raises:

Type Description
AssertionError

If data length doesn't match shape product.

Source code in py_misc_utils/utils.py
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
def flat2shape(data, shape):
  """Reshape flat data into a nested list structure matching the given shape.

  Args:
    data: Flat sequence of data elements.
    shape: Target shape as a sequence of dimensions.

  Returns:
    Nested list structure matching the shape.

  Raises:
    AssertionError: If data length doesn't match shape product.
  """
  tas.check_eq(len(data),
               np.prod(shape),
               msg=f'Shape {shape} is unsuitable for a {len(data)} long array')

  # For an Mx...xK input shape, return a M elements (nested) list.
  for n in reversed(shape[1:]):
    data = [data[i:i + n] for i in range(len(data), n)]

  return data

shape2flat(data, shape)

Flatten a nested data structure into a flat tuple.

Parameters:

Name Type Description Default
data

Nested iterable structure.

required
shape

Expected shape of the data.

required

Returns:

Type Description

Flat tuple of all elements.

Raises:

Type Description
AssertionError

If data structure doesn't match shape.

Source code in py_misc_utils/utils.py
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
def shape2flat(data, shape):
  """Flatten a nested data structure into a flat tuple.

  Args:
    data: Nested iterable structure.
    shape: Expected shape of the data.

  Returns:
    Flat tuple of all elements.

  Raises:
    AssertionError: If data structure doesn't match shape.
  """
  for _ in range(len(shape) - 1):
    tas.check(hasattr(data, '__iter__'), msg=f'Wrong data type: {type(data)}')
    ndata = []
    for av in data:
      tas.check(hasattr(av, '__iter__'), msg=f'Wrong data type: {type(data)}')
      ndata.extend(av)

    data = ndata

  tas.check_eq(len(data),
               np.prod(shape),
               msg=f'Shape {shape} is unsuitable for a {len(data)} long array')

  return tuple(data)

binary_reduce(parts, reduce_fn)

Reduce a sequence pairwise, halving it at every step.

Parameters:

Name Type Description Default
parts

Sequence of values to reduce; its length does not need to be a power of two.

required
reduce_fn

Callable combining two values into one.

required

Returns:

Type Description

The single reduced value.

Source code in py_misc_utils/utils.py
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
def binary_reduce(parts, reduce_fn):
  """Reduce a sequence pairwise, halving it at every step.

  Args:
    parts: Sequence of values to reduce; its length does not need to be
      a power of two.
    reduce_fn: Callable combining two values into one.

  Returns:
    The single reduced value.
  """
  while len(parts) > 1:
    nparts, base = [], 0
    if len(parts) % 2 != 0:
      nparts.append(parts[0])
      base = 1

    nparts.extend(
        reduce_fn(parts[i], parts[i + 1]) for i in range(base,
                                                         len(parts) - 1, 2))

    parts = nparts

  return parts[0]

stringify(s)

Convert every leaf value of a nested structure into a string.

Parameters:

Name Type Description Default
s

Nested structure of lists, tuples and dictionaries.

required

Returns:

Type Description

The structure with every non-container leaf converted with str().

Source code in py_misc_utils/utils.py
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
def stringify(s):
  """Convert every leaf value of a nested structure into a string.

  Args:
    s: Nested structure of lists, tuples and dictionaries.

  Returns:
    The structure with every non-container leaf converted with str().
  """

  def rwfn(v):
    """Return the string form of a non-container leaf value."""
    if not (isinstance(v, (list, tuple)) or cu.isdict(v)):
      return str(v)

  return cu.data_rewrite(s, rwfn)

seq_rewrite(seq, sd)

Rewrite the elements of a sequence using a substitution dict.

Parameters:

Name Type Description Default
seq

Sequence whose elements are rewritten.

required
sd

Dict mapping original elements to their replacement; elements not in the dict are kept as-is.

required

Returns:

Type Description

A sequence of the same type of seq with the rewritten elements.

Source code in py_misc_utils/utils.py
942
943
944
945
946
947
948
949
950
951
952
953
def seq_rewrite(seq, sd):
  """Rewrite the elements of a sequence using a substitution dict.

  Args:
    seq: Sequence whose elements are rewritten.
    sd: Dict mapping original elements to their replacement; elements
      not in the dict are kept as-is.

  Returns:
    A sequence of the same type of seq with the rewritten elements.
  """
  return type(seq)(sd.get(s, s) for s in seq)

dfetch(d, *args)

Fetch multiple keys from a dictionary, requiring them to be present.

Parameters:

Name Type Description Default
d

Dictionary to query.

required
*args

Keys to retrieve.

()

Returns:

Type Description

A tuple with the values of the keys.

Raises:

Type Description
KeyError

When a key is missing.

Source code in py_misc_utils/utils.py
956
957
958
959
960
961
962
963
964
965
966
967
968
969
def dfetch(d, *args):
  """Fetch multiple keys from a dictionary, requiring them to be present.

  Args:
    d: Dictionary to query.
    *args: Keys to retrieve.

  Returns:
    A tuple with the values of the keys.

  Raises:
    KeyError: When a key is missing.
  """
  return tuple(d[n] for n in args)

numel(t)

Return the number of elements of a tensor-like object.

Parameters:

Name Type Description Default
t

Object with a shape attribute or a sized sequence.

required

Returns:

Type Description

The product of the shape entries, or the length of t when the shape

is missing.

Source code in py_misc_utils/utils.py
972
973
974
975
976
977
978
979
980
981
982
983
984
def numel(t):
  """Return the number of elements of a tensor-like object.

  Args:
    t: Object with a shape attribute or a sized sequence.

  Returns:
    The product of the shape entries, or the length of t when the shape
    is missing.
  """
  sp = cu.get_property(t, 'shape')

  return np.prod(sp) if sp is not None else len(t)

scale_data(data, base_data, scale)

Compute scaled differences against a base sequence.

Parameters:

Name Type Description Default
data

Sequence of values to scale.

required
base_data

Sequence of reference values the differences are computed against.

required
scale

Multiplier applied to the relative differences.

required

Returns:

Type Description

The sequence of scaled values.

Source code in py_misc_utils/utils.py
987
988
989
990
991
992
993
994
995
996
997
998
999
def scale_data(data, base_data, scale):
  """Compute scaled differences against a base sequence.

  Args:
    data: Sequence of values to scale.
    base_data: Sequence of reference values the differences are computed
      against.
    scale: Multiplier applied to the relative differences.

  Returns:
    The sequence of scaled values.
  """
  return ((data - base_data) / base_data) * scale

array_code(size)

Return the array module typecode for a byte size.

Parameters:

Name Type Description Default
size

Number of bytes to represent.

required

Returns:

Type Description

The typecode of the smallest unsigned integer array type able to hold

size bytes.

Raises:

Type Description
ValueError

When size does not fit any of the supported types.

Source code in py_misc_utils/utils.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
def array_code(size):
  """Return the array module typecode for a byte size.

  Args:
    size: Number of bytes to represent.

  Returns:
    The typecode of the smallest unsigned integer array type able to hold
    size bytes.

  Raises:
    ValueError: When size does not fit any of the supported types.
  """
  nbytes = math.ceil(math.log2(size)) / 8
  for cb, code in _ARRAY_SIZES:
    if cb >= nbytes:
      return code

  alog.xraise(ValueError, f'Size {size} too big to fit inside any array integer types')

checked_remove(l, o)

Remove an element from a list, tolerating missing elements.

Parameters:

Name Type Description Default
l

List to remove the element from.

required
o

Element to remove.

required

Returns:

Type Description

True when the element was removed, False when it was not present.

Source code in py_misc_utils/utils.py
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
def checked_remove(l, o):
  """Remove an element from a list, tolerating missing elements.

  Args:
    l: List to remove the element from.
    o: Element to remove.

  Returns:
    True when the element was removed, False when it was not present.
  """
  try:
    l.remove(o)
  except ValueError:
    return False

  return True

sleep_until(date, msg=None)

Sleep until a target datetime is reached.

Parameters:

Name Type Description Default
date

Timezone-aware target datetime.

required
msg

Optional message logged before sleeping.

None
Source code in py_misc_utils/utils.py
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def sleep_until(date, msg=None):
  """Sleep until a target datetime is reached.

  Args:
    date: Timezone-aware target datetime.
    msg: Optional message logged before sleeping.
  """
  now = datetime.datetime.now(tz=date.tzinfo)
  if date > now:
    if msg:
      alog.info(msg)
    time.sleep(date.timestamp() - now.timestamp())

parse_dict(data)

Parse a YAML string into a dictionary.

Parameters:

Name Type Description Default
data

YAML string to parse.

required

Returns:

Type Description

The parsed dictionary.

Source code in py_misc_utils/utils.py
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
def parse_dict(data):
  """Parse a YAML string into a dictionary.

  Args:
    data: YAML string to parse.

  Returns:
    The parsed dictionary.
  """
  return yaml.safe_load(data)

parse_args(in_args)

Parse comma-separated arguments into positional args and kwargs.

Parameters:

Name Type Description Default
in_args

Comma-separated string, or sequence of strings; entries containing '=' become keyword arguments and their values are parsed as YAML, the remaining entries become positional arguments.

required

Returns:

Type Description

A tuple with the list of positional arguments and the dict of keyword

arguments.

Raises:

Type Description
ValueError

When an entry has more than one '='.

Source code in py_misc_utils/utils.py
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
def parse_args(in_args):
  """Parse comma-separated arguments into positional args and kwargs.

  Args:
    in_args: Comma-separated string, or sequence of strings; entries
      containing '=' become keyword arguments and their values are
      parsed as YAML, the remaining entries become positional arguments.

  Returns:
    A tuple with the list of positional arguments and the dict of keyword
    arguments.

  Raises:
    ValueError: When an entry has more than one '='.
  """
  seq_args = comma_split(in_args) if isinstance(in_args, str) else in_args

  args, kwargs = [], dict()
  for arg in seq_args:
    parts = cu.separate(arg, '=')
    if len(parts) == 2:
      kwargs[parts[0]] = yaml.safe_load(parts[1])
    elif len(parts) == 1:
      args.append(yaml.safe_load(parts[0]))
    else:
      alog.xraise(ValueError, f'Syntax error: {arg}')

  return args, kwargs

state_update(path, **kwargs)

Load, update and persist a pickled state dictionary.

Parameters:

Name Type Description Default
path

Path or URL of the file holding the pickled state; missing files yield an empty state.

required
**kwargs

Key/value pairs merged into the state; when no pair is given the state is only loaded.

{}

Returns:

Type Description

The updated state dictionary.

Source code in py_misc_utils/utils.py
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
def state_update(path, **kwargs):
  """Load, update and persist a pickled state dictionary.

  Args:
    path: Path or URL of the file holding the pickled state; missing
      files yield an empty state.
    **kwargs: Key/value pairs merged into the state; when no pair is
      given the state is only loaded.

  Returns:
    The updated state dictionary.
  """
  if sfile := gfs.maybe_open(path, mode='rb'):
    with sfile as fd:
      state = pickle.load(fd)
  else:
    state = dict()

  if kwargs:
    state.update(kwargs)
    with fow.FileOverwrite(path, mode='wb') as f:
      pickle.dump(state, f, protocol=pickle_proto())

  return state

copy_inplace(dest, src)

Copy the attributes of an object into another one in place.

Parameters:

Name Type Description Default
dest

Object to copy the attributes into; objects without dict copy their slots instead.

required
src

Object to copy the attributes from.

required

Returns:

Type Description

The dest object updated in place.

Source code in py_misc_utils/utils.py
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
def copy_inplace(dest, src):
  """Copy the attributes of an object into another one in place.

  Args:
    dest: Object to copy the attributes into; objects without __dict__
      copy their slots instead.
    src: Object to copy the attributes from.

  Returns:
    The dest object updated in place.
  """
  obj_dict = getattr(dest, '__dict__', None)
  if obj_dict is not None:
    obj_dict.update(src.__dict__)
  else:
    for slot in iu.class_slots(dest):
      setattr(dest, slot, getattr(src, slot, None))

  return dest