Coverage for C: \ Users \ peaco \ OneDrive \ Documents \ GitHub \ mt_metadata \ mt_metadata \ helper_functions.py: 82%
17 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-10 00:11 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-10 00:11 -0800
1"""
2This module has some general helper functions that it isn't yet clear where they should live.
4These may not be needed at all after the pydantic upgrade is fully integrated.
5"""
7from typing import Dict, List, Union
9from mt_metadata.base import MetadataBase
12"""
13 Here are some rather abstract functions for generalizing setters of lists,
14 whose elements are particular mt_metadata classes.
15 Example usage is decimation_level.bands
17"""
20def validate_setter_input(
21 value: Union[Dict, MetadataBase], expected_class: MetadataBase
22) -> List:
23 """
24 Takes a setter's input and makes it a list if it not.
25 Then asserts that every list element is of permissible type (dict or expected class)
27 Parameters
28 ----------
29 value: Union[Dict, Base]
30 The input to the setter.
32 expected_class: Base
33 Some mt_metadata class that we want the setter work with
35 Returns
36 -------
37 value: list
38 List of elements for the setter all of type expected_class or dict.
39 """
40 # Handle singleton cases
41 if isinstance(value, (expected_class, dict)):
42 value = [value]
44 if not isinstance(value, list):
45 raise TypeError(f"Not sure what to do with {type(value)}")
47 return value
50def cast_to_class_if_dict(
51 obj: Union[Dict, MetadataBase], cls: MetadataBase
52) -> MetadataBase:
53 """
55 Parameters
56 ----------
57 obj: Union[Dict, MetadataBase]
58 Either an mt_metadata object or its dict representaiton
59 cls: MetadataBase
60 Some mt_metadata object that we want to get back
62 Returns
63 -------
64 either the input or the input dict cast to an mt_metadata object.
65 """
66 if not isinstance(obj, (cls, dict)):
67 raise TypeError(
68 f"List entry must be a {cls().__class__} object not {type(obj)}"
69 )
70 if isinstance(obj, dict):
71 mt_metadata_obj = cls()
72 mt_metadata_obj.from_dict(obj)
73 else:
74 mt_metadata_obj = obj
76 return mt_metadata_obj