Skip to content

ParamsDict

Bases: dict

A dictionary subclass that ensures all keys are strings and supports multiple key- value assignments at once, with validation against a list of valid keys.

This class is designed to be used for passing parameters to HTTP requests and extends the base dictionary class, ensuring that insertion order is preserved.

Source code in yeastdnnexplorer/interface/ParamsDict.py
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
class ParamsDict(dict):
    """
    A dictionary subclass that ensures all keys are strings and supports multiple key-
    value assignments at once, with validation against a list of valid keys.

    This class is designed to be used for passing parameters to HTTP requests and
    extends the base dictionary class, ensuring that insertion order is preserved.

    """

    def __init__(self, params: dict[str, Any] = {}, valid_keys: list[str] = []) -> None:
        """
        Initialize the ParamsDict with optional initial parameters and valid keys.

        :param params: A dictionary of initial parameters. All keys must be strings.
        :type params: dict, optional
        :param valid_keys: A list of valid keys for validation.
        :type valid_keys: list of str, optional
        :raises ValueError: If `params` is not a dictionary or if any of the keys
            are not strings.

        """
        params = params or {}
        valid_keys = valid_keys or []
        if not isinstance(params, dict):
            raise ValueError("params must be a dictionary")
        if len(params) > 0 and not all(isinstance(k, str) for k in params.keys()):
            raise ValueError("params must be a dictionary with string keys")
        super().__init__(params)
        self._valid_keys = valid_keys

    def __setitem__(self, key: str | list[str], value: Any | list[Any]) -> None:
        """
        Set a parameter value or multiple parameter values.

        :param key: The parameter key or a list of parameter keys.
        :type key: str or list of str
        :param value: The parameter value or a list of parameter values.
        :type value: any or list of any
        :raises ValueError: If the length of `key` and `value` lists do not match.
        :raises KeyError: If `key` is not a string or a list of strings.

        """
        if isinstance(key, str):
            self._validate_key(key)
            super().__setitem__(key, value)
        elif isinstance(key, list) and isinstance(value, list):
            if len(key) != len(value):
                raise ValueError("Length of keys and values must match")
            for k, v in zip(key, value):
                if not isinstance(k, str):
                    raise KeyError("All keys must be strings")
                self._validate_key(k)
                super().__setitem__(k, v)
        else:
            raise KeyError("Key must be a string or list of strings")

    def __getitem__(self, key: str | list[str]) -> Union[Any, "ParamsDict"]:
        """
        Get a parameter value or a new ParamsDict with specified keys.

        :param key: The parameter key or a list of parameter keys.
        :type key: str or list of str
        :return: The parameter value or a new ParamsDict with the specified keys.
        :rtype: any or ParamsDict
        :raises KeyError: If `key` is not a string or a list of strings.

        """
        if isinstance(key, str):
            return super().__getitem__(key)
        elif isinstance(key, list):
            return ParamsDict({k: dict.__getitem__(self, k) for k in key if k in self})
        else:
            raise KeyError("Key must be a string or list of strings")

    def __delitem__(self, key: str) -> None:
        """
        Delete a parameter by key.

        :param key: The parameter key.
        :type key: str
        :raises KeyError: If `key` is not a string.

        """
        if isinstance(key, str):
            super().__delitem__(key)
        else:
            raise KeyError("Key must be a string")

    def __repr__(self) -> str:
        """
        Return a string representation of the ParamsDict.

        :return: A string representation of the ParamsDict.
        :rtype: str

        """
        return f"ParamsDict({super().__repr__()})"

    def __str__(self) -> str:
        """
        Return a human-readable string representation of the ParamsDict.

        :return: A human-readable string representation of the ParamsDict.
        :rtype: str

        """
        return ", ".join(f"{k}: {v}" for k, v in self.items())

    def update(self, *args, **kwargs) -> None:
        """Update the ParamsDict with the key/value pairs from other, overwriting
        existing keys."""
        if args:
            other = args[0]
            if isinstance(other, dict):
                [self._validate_key(k) for k in other.keys()]
                for key, value in other.items():
                    self.__setitem__(key, value)
            else:
                [self._validate_key(k) for k, _ in other]
                for key, value in other:
                    self.__setitem__(key, value)
        [self._validate_key(k) for k in kwargs.keys()]
        for key, value in kwargs.items():
            self.__setitem__(key, value)

    def as_dict(self) -> dict:
        """
        Convert the ParamsDict to a standard dictionary.

        :return: A standard dictionary with the same items as the ParamsDict.
        :rtype: dict

        """
        return dict(self)

    def _validate_key(self, key: str) -> bool:
        """Validate that the key is in the list of valid keys."""
        if self._valid_keys and key not in self._valid_keys:
            raise KeyError(f"Invalid parameter key provided: {key}")
        return True

    @property
    def valid_keys(self) -> list[str]:
        """Get the list of valid keys."""
        return self._valid_keys

    @valid_keys.setter
    def valid_keys(self, keys: list[str]) -> None:
        """Set the list of valid keys."""
        if not all(isinstance(k, str) for k in keys):
            raise ValueError("valid_keys must be a list of strings")
        self._valid_keys = keys

valid_keys: list[str] property writable

Get the list of valid keys.

__delitem__(key)

Delete a parameter by key.

Parameters:

Name Type Description Default
key str

The parameter key.

required

Raises:

Type Description
KeyError

If key is not a string.

Source code in yeastdnnexplorer/interface/ParamsDict.py
79
80
81
82
83
84
85
86
87
88
89
90
91
def __delitem__(self, key: str) -> None:
    """
    Delete a parameter by key.

    :param key: The parameter key.
    :type key: str
    :raises KeyError: If `key` is not a string.

    """
    if isinstance(key, str):
        super().__delitem__(key)
    else:
        raise KeyError("Key must be a string")

__getitem__(key)

Get a parameter value or a new ParamsDict with specified keys.

Parameters:

Name Type Description Default
key str | list[str]

The parameter key or a list of parameter keys.

required

Returns:

Type Description
any | ParamsDict

The parameter value or a new ParamsDict with the specified keys.

Raises:

Type Description
KeyError

If key is not a string or a list of strings.

Source code in yeastdnnexplorer/interface/ParamsDict.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def __getitem__(self, key: str | list[str]) -> Union[Any, "ParamsDict"]:
    """
    Get a parameter value or a new ParamsDict with specified keys.

    :param key: The parameter key or a list of parameter keys.
    :type key: str or list of str
    :return: The parameter value or a new ParamsDict with the specified keys.
    :rtype: any or ParamsDict
    :raises KeyError: If `key` is not a string or a list of strings.

    """
    if isinstance(key, str):
        return super().__getitem__(key)
    elif isinstance(key, list):
        return ParamsDict({k: dict.__getitem__(self, k) for k in key if k in self})
    else:
        raise KeyError("Key must be a string or list of strings")

__init__(params={}, valid_keys=[])

Initialize the ParamsDict with optional initial parameters and valid keys.

Parameters:

Name Type Description Default
params dict[str, Any]

A dictionary of initial parameters. All keys must be strings.

{}
valid_keys list[str]

A list of valid keys for validation.

[]

Raises:

Type Description
ValueError

If params is not a dictionary or if any of the keys are not strings.

Source code in yeastdnnexplorer/interface/ParamsDict.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def __init__(self, params: dict[str, Any] = {}, valid_keys: list[str] = []) -> None:
    """
    Initialize the ParamsDict with optional initial parameters and valid keys.

    :param params: A dictionary of initial parameters. All keys must be strings.
    :type params: dict, optional
    :param valid_keys: A list of valid keys for validation.
    :type valid_keys: list of str, optional
    :raises ValueError: If `params` is not a dictionary or if any of the keys
        are not strings.

    """
    params = params or {}
    valid_keys = valid_keys or []
    if not isinstance(params, dict):
        raise ValueError("params must be a dictionary")
    if len(params) > 0 and not all(isinstance(k, str) for k in params.keys()):
        raise ValueError("params must be a dictionary with string keys")
    super().__init__(params)
    self._valid_keys = valid_keys

__repr__()

Return a string representation of the ParamsDict.

Returns:

Type Description
str

A string representation of the ParamsDict.

Source code in yeastdnnexplorer/interface/ParamsDict.py
 93
 94
 95
 96
 97
 98
 99
100
101
def __repr__(self) -> str:
    """
    Return a string representation of the ParamsDict.

    :return: A string representation of the ParamsDict.
    :rtype: str

    """
    return f"ParamsDict({super().__repr__()})"

__setitem__(key, value)

Set a parameter value or multiple parameter values.

Parameters:

Name Type Description Default
key str | list[str]

The parameter key or a list of parameter keys.

required
value Any | list[Any]

The parameter value or a list of parameter values.

required

Raises:

Type Description
ValueError

If the length of key and value lists do not match.

KeyError

If key is not a string or a list of strings.

Source code in yeastdnnexplorer/interface/ParamsDict.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def __setitem__(self, key: str | list[str], value: Any | list[Any]) -> None:
    """
    Set a parameter value or multiple parameter values.

    :param key: The parameter key or a list of parameter keys.
    :type key: str or list of str
    :param value: The parameter value or a list of parameter values.
    :type value: any or list of any
    :raises ValueError: If the length of `key` and `value` lists do not match.
    :raises KeyError: If `key` is not a string or a list of strings.

    """
    if isinstance(key, str):
        self._validate_key(key)
        super().__setitem__(key, value)
    elif isinstance(key, list) and isinstance(value, list):
        if len(key) != len(value):
            raise ValueError("Length of keys and values must match")
        for k, v in zip(key, value):
            if not isinstance(k, str):
                raise KeyError("All keys must be strings")
            self._validate_key(k)
            super().__setitem__(k, v)
    else:
        raise KeyError("Key must be a string or list of strings")

__str__()

Return a human-readable string representation of the ParamsDict.

Returns:

Type Description
str

A human-readable string representation of the ParamsDict.

Source code in yeastdnnexplorer/interface/ParamsDict.py
103
104
105
106
107
108
109
110
111
def __str__(self) -> str:
    """
    Return a human-readable string representation of the ParamsDict.

    :return: A human-readable string representation of the ParamsDict.
    :rtype: str

    """
    return ", ".join(f"{k}: {v}" for k, v in self.items())

as_dict()

Convert the ParamsDict to a standard dictionary.

Returns:

Type Description
dict

A standard dictionary with the same items as the ParamsDict.

Source code in yeastdnnexplorer/interface/ParamsDict.py
130
131
132
133
134
135
136
137
138
def as_dict(self) -> dict:
    """
    Convert the ParamsDict to a standard dictionary.

    :return: A standard dictionary with the same items as the ParamsDict.
    :rtype: dict

    """
    return dict(self)

update(*args, **kwargs)

Update the ParamsDict with the key/value pairs from other, overwriting existing keys.

Source code in yeastdnnexplorer/interface/ParamsDict.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def update(self, *args, **kwargs) -> None:
    """Update the ParamsDict with the key/value pairs from other, overwriting
    existing keys."""
    if args:
        other = args[0]
        if isinstance(other, dict):
            [self._validate_key(k) for k in other.keys()]
            for key, value in other.items():
                self.__setitem__(key, value)
        else:
            [self._validate_key(k) for k, _ in other]
            for key, value in other:
                self.__setitem__(key, value)
    [self._validate_key(k) for k in kwargs.keys()]
    for key, value in kwargs.items():
        self.__setitem__(key, value)