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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
value_or(v, defval)
¶
Return v, or defval when v is None.
Source code in py_misc_utils/utils.py
566 567 568 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |