|
17 | 17 | 'DictMethod',
|
18 | 18 | 'DictPop',
|
19 | 19 | 'DictPopitem',
|
| 20 | + 'DictSetDefault', |
20 | 21 | )
|
21 | 22 |
|
22 | 23 | #==============================================================================
|
@@ -176,4 +177,62 @@ def default_value(self):
|
176 | 177 | """
|
177 | 178 | return self._args[1]
|
178 | 179 |
|
| 180 | +#============================================================================== |
| 181 | + |
| 182 | +class DictSetDefault(DictMethod): |
| 183 | + """ |
| 184 | + Represents a call to the .setdefault() method. |
| 185 | +
|
| 186 | + The setdefault() method set an element in the dict. The element is set |
| 187 | + via a key and a value. If the value is not passed then default value is set |
| 188 | + as the value. |
| 189 | +
|
| 190 | + If returns the value and if it is not present in the dictionary then the default |
| 191 | + value is returned. |
| 192 | +
|
| 193 | + Parameters |
| 194 | + ---------- |
| 195 | + dict_obj : TypedAstNode |
| 196 | + The object from which the method is called. |
| 197 | +
|
| 198 | + k : TypedAstNode |
| 199 | + The key which is used to set the value from the dictionary. |
| 200 | +
|
| 201 | + d : TypedAstNode, optional |
| 202 | + The value that should be returned. if the value is not present in the |
| 203 | + dictionary then default value is returned. |
| 204 | + """ |
| 205 | + __slots__ = ('_class_type', '_shape') |
| 206 | + name = 'setdefault' |
| 207 | + |
| 208 | + def __init__(self, dict_obj, k, d = None): |
| 209 | + dict_type = dict_obj.class_type |
| 210 | + self._class_type = dict_type.value_type |
| 211 | + |
| 212 | + self._shape = (None) * self._class_type.rank if self._class_type.rank else None |
179 | 213 |
|
| 214 | + if k.class_type != dict_type.key_type: |
| 215 | + raise TypeError(f"Key passed to setdefault method has type {k.class_type}. Expected {dict_type.key_type}") |
| 216 | + if d is None: |
| 217 | + raise TypeError("None cannot be used as the default argument for the setdefault method.") |
| 218 | + if d and d.class_type != dict_type.value_type: |
| 219 | + raise TypeError(f"Default value passed to setdefault method has type {d.class_type}. Expected {dict_type.value_type}") |
| 220 | + super().__init__(dict_obj, k, d) |
| 221 | + |
| 222 | + @property |
| 223 | + def key(self): |
| 224 | + """ |
| 225 | + The key that is used to select the element from the dict. |
| 226 | +
|
| 227 | + The key that is used to select the element from the dict. |
| 228 | + """ |
| 229 | + return self._args[0] |
| 230 | + |
| 231 | + @property |
| 232 | + def default_value(self): |
| 233 | + """ |
| 234 | + The value that should be returned if the key is not present in the dictionary. |
| 235 | +
|
| 236 | + The value that should be returned if the key is not present in the dictionary. |
| 237 | + """ |
| 238 | + return self._args[1] |
0 commit comments