| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
"""Module for spliting flag prefixes.""" |
| 16 |
|
| 17 |
import ast |
| 18 |
import dataclasses as dc |
| 19 |
import functools |
| 20 |
import types |
| 21 |
import typing |
| 22 |
from typing import Any, MutableSequence, Optional, Sequence, Tuple, Union, Type |
| 23 |
|
| 24 |
from ml_collections import config_dict |
| 25 |
|
| 26 |
|
| 27 |
NoneType = type(None) |
| 28 |
|
| 29 |
|
| 30 |
_AST_SPLIT_CONFIG_PATH = { |
| 31 |
ast.Attribute: lambda n: (*_split_node(n.value), n.attr), |
| 32 |
ast.Index: lambda i: _split_node(i.value), |
| 33 |
ast.Name: lambda n: (n.id,), |
| 34 |
ast.Slice: lambda i: slice(*map(_split_node, (i.lower, i.upper, i.step))), |
| 35 |
ast.Subscript: lambda n: (*_split_node(n.value), _split_node(n.slice)), |
| 36 |
type(None): lambda n: None |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
def _split_node(node): |
| 41 |
return _AST_SPLIT_CONFIG_PATH.get(type(node), ast.literal_eval)(node) |
| 42 |
|
| 43 |
|
| 44 |
def split(config_path: str) -> Tuple[Any]: |
| 45 |
"""Returns config_path split into a tuple of parts. |
| 46 |
|
| 47 |
Example usage: |
| 48 |
>>> assert config_path.split('a.b.cc') == ('a', 'b', 'cc') |
| 49 |
>>> assert config_path.split('a.b["cc.d"]') == ('a', 'b', 'cc.d') |
| 50 |
>>> assert config_path.split('a.b[10]') == ('a', 'b', 10) |
| 51 |
>>> assert config_path.split('a[(1, 2)]') == ('a', (1, 2)) |
| 52 |
>>> assert config_path.split('a[:]') == ('a', slice(None)) |
| 53 |
|
| 54 |
Args: |
| 55 |
config_path: Input path to be split - see example usage. |
| 56 |
|
| 57 |
Returns: |
| 58 |
Tuple of config_path split into parts. Parts are attributes or subscripts. |
| 59 |
Attrributes are treated as strings and subscripts are parsed using |
| 60 |
ast.literal_eval. It is up to the caller to ensure all returned types are |
| 61 |
valid. |
| 62 |
|
| 63 |
Raises: |
| 64 |
ValueError: Failed to parse config_path. |
| 65 |
""" |
| 66 |
try: |
| 67 |
node = ast.parse(config_path, mode='eval') |
| 68 |
except SyntaxError as e: |
| 69 |
raise ValueError(f'Could not parse {config_path!r}: {e!r}') from None |
| 70 |
if isinstance(node, ast.Expression): |
| 71 |
result = _split_node(node.body) |
| 72 |
if isinstance(result, tuple): |
| 73 |
return result |
| 74 |
raise ValueError(config_path) |
| 75 |
|
| 76 |
|
| 77 |
def _get_item_or_attribute(config, field, |
| 78 |
field_path: Optional[str] = None): |
| 79 |
"""Returns attribute of member failing that the item.""" |
| 80 |
if isinstance(field, str) and hasattr(config, field): |
| 81 |
return getattr(config, field) |
| 82 |
if hasattr(config, '__getitem__'): |
| 83 |
return config[field] |
| 84 |
if isinstance(field, int): |
| 85 |
raise IndexError( |
| 86 |
f'{type(config)} does not support integer indexing [{field}]]. ' |
| 87 |
f'Attempting to lookup: {field_path}') |
| 88 |
raise KeyError( |
| 89 |
f'Attribute {type(config)}.{field} does not exist ' |
| 90 |
'and the type does not support indexing. ' |
| 91 |
f'Attempting to lookup: {field_path}') |
| 92 |
|
| 93 |
|
| 94 |
def _get_holder_field(config_path: str, config: Any) -> Tuple[Any, str]: |
| 95 |
"""Returns the last part config_path and config to allow assignment. |
| 96 |
|
| 97 |
Example usage: |
| 98 |
>>> config = {'a': {'b', {'c', 10}}} |
| 99 |
>>> holder, lastfield = _get_holder_field('a.b.c', config) |
| 100 |
>>> assert lastfield == 'c' |
| 101 |
>>> assert holder is config['a']['b'] |
| 102 |
>>> assert holder[lastfield] == 10 |
| 103 |
|
| 104 |
Args: |
| 105 |
config_path: Any string that `split` can process. |
| 106 |
config: A nested datastructure that can be accessed via |
| 107 |
_get_item_or_attribute |
| 108 |
|
| 109 |
Returns: |
| 110 |
The penultimate object when walking config with config_path. And the final |
| 111 |
part of the config path. |
| 112 |
|
| 113 |
Raises: |
| 114 |
IndexError: Integer field not found in nested structure. |
| 115 |
KeyError: Non-integer field not found in nested structure. |
| 116 |
ValueError: Empty/invalid config_path after parsing. |
| 117 |
""" |
| 118 |
fields = split(config_path) |
| 119 |
if not fields: |
| 120 |
raise ValueError('Path cannot be empty') |
| 121 |
get_item = functools.partial(_get_item_or_attribute, field_path=config_path) |
| 122 |
holder = functools.reduce(get_item, fields[:-1], config) |
| 123 |
return holder, fields[-1] |
| 124 |
|
| 125 |
|
| 126 |
def get_value(config_path: str, config: Any): |
| 127 |
"""Gets value of a single field. |
| 128 |
|
| 129 |
Example usage: |
| 130 |
>>> config = {'a': {'b', {'c', 10}}} |
| 131 |
>>> assert config_path.get_value('a.b.c', config) == 10 |
| 132 |
|
| 133 |
Args: |
| 134 |
config_path: Any string that `split` can process. |
| 135 |
config: A nested datastructure |
| 136 |
|
| 137 |
Returns: |
| 138 |
The last object when walking config with config_path. |
| 139 |
|
| 140 |
Raises: |
| 141 |
IndexError: Integer field not found in nested structure. |
| 142 |
KeyError: Non-integer field not found in nested structure. |
| 143 |
ValueError: Empty/invalid config_path after parsing. |
| 144 |
""" |
| 145 |
get_item = functools.partial(_get_item_or_attribute, field_path=config_path) |
| 146 |
return functools.reduce(get_item, split(config_path), config) |
| 147 |
|
| 148 |
|
| 149 |
def initialize_missing_parent_fields( |
| 150 |
config: Any, override: str, |
| 151 |
allowed_missing: Sequence[str]): |
| 152 |
"""Adds some missing nested holder fields for a particular override. |
| 153 |
|
| 154 |
For example if override is 'config.a.b.c' and config.a is None, it |
| 155 |
will default initialize config.a, and if config.a.b is None will default |
| 156 |
initialize it as well. Only overrides present in allowed_missing will |
| 157 |
be initialized. |
| 158 |
|
| 159 |
Args: |
| 160 |
config: config object (typically dataclass) |
| 161 |
override: dot joined override name. |
| 162 |
allowed_missing: list of overrides that are allowed |
| 163 |
to be set. For example, if override is 'a.b.c.d', |
| 164 |
allowed_missing could be ['a.b.c', 'a', 'foo.bar']. |
| 165 |
|
| 166 |
Raises: |
| 167 |
ValueError: if parent field is not of dataclass type. |
| 168 |
""" |
| 169 |
fields = split(override) |
| 170 |
|
| 171 |
allowed_levels = {len(split(x)) for x in allowed_missing if |
| 172 |
override.startswith(x + '.')} |
| 173 |
child = config |
| 174 |
for level, f in enumerate(fields[:-1], 1): |
| 175 |
parent = child |
| 176 |
child = _get_item_or_attribute(parent, f, override) |
| 177 |
if child is not None: |
| 178 |
continue |
| 179 |
|
| 180 |
field_type = get_type(f, parent) |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
if not dc.is_dataclass(field_type): |
| 187 |
raise ValueError( |
| 188 |
f'Override {override} can not be applied because ' |
| 189 |
f'field "{f}" is None, and its type "{field_type}" is not a ' |
| 190 |
f'dataclass in the parent of type "{type(parent)}".') |
| 191 |
|
| 192 |
if level not in allowed_levels: |
| 193 |
raise ValueError( |
| 194 |
f'Flag {override} can not be applied because ' |
| 195 |
f'field "{f}" is None by default and it is not explicitly ' |
| 196 |
'provided in flags (it can be default intialized by ' |
| 197 |
f'providing --<path-to-{f}>.{f}=build flag') |
| 198 |
try: |
| 199 |
child = field_type() |
| 200 |
except Exception as e: |
| 201 |
raise ValueError( |
| 202 |
f'Override {override} can not be applied because ' |
| 203 |
f'field "{f}" of type {field_type} can not be default instantiated:' |
| 204 |
f'{e}') from e |
| 205 |
set_value(f, parent, child) |
| 206 |
|
| 207 |
|
| 208 |
def get_origin(type_spec: type) -> Optional[type]: |
| 209 |
"""Call typing.get_origin, with a fallback for Python 3.7 and below.""" |
| 210 |
if hasattr(typing, 'get_origin'): |
| 211 |
return typing.get_origin(type_spec) |
| 212 |
return getattr(type_spec, '__origin__', None) |
| 213 |
|
| 214 |
|
| 215 |
def get_args(type_spec: type) -> Union[NoneType, Tuple[type, ...]]: |
| 216 |
"""Call typing.get_args, with fallback for Python 3.7 and below.""" |
| 217 |
if hasattr(typing, 'get_args'): |
| 218 |
return typing.get_args(type_spec) |
| 219 |
return getattr(type_spec, '__args__', NoneType) |
| 220 |
|
| 221 |
|
| 222 |
def _is_union_type(type_spec: type) -> bool: |
| 223 |
"""Cheeck if a type_spec is a Union type or not.""" |
| 224 |
|
| 225 |
|
| 226 |
return get_origin(type_spec) in [Union, getattr(types, 'UnionType', Union)] |
| 227 |
|
| 228 |
|
| 229 |
def extract_type_from_optional(type_spec: type) -> Optional[type]: |
| 230 |
"""If type_spec is of type Optional[T], returns T object, otherwise None""" |
| 231 |
if not _is_union_type(type_spec): |
| 232 |
return None |
| 233 |
non_none = [t for t in get_args(type_spec) if t is not NoneType] |
| 234 |
if len(non_none) != 1: |
| 235 |
return None |
| 236 |
return non_none[0] |
| 237 |
|
| 238 |
|
| 239 |
def normalize_type(type_spec: type) -> type: |
| 240 |
"""Normalizes a type object. |
| 241 |
|
| 242 |
Strips all None types from the type specification and returns the remaining |
| 243 |
single type. This is primarily useful for Optional type annotations in which |
| 244 |
case it will strip out the NoneType and return the inner type. |
| 245 |
|
| 246 |
Args: |
| 247 |
type_spec: The type to normalize. |
| 248 |
|
| 249 |
Raises: |
| 250 |
TypeError: If there is not exactly 1 non-None type in the union. |
| 251 |
Returns: |
| 252 |
The normalized type. |
| 253 |
""" |
| 254 |
if _is_union_type(type_spec): |
| 255 |
subtype = extract_type_from_optional(type_spec) |
| 256 |
if subtype is None: |
| 257 |
raise TypeError(f'Unable to normalize ambiguous type: {type_spec}') |
| 258 |
return subtype |
| 259 |
|
| 260 |
return type_spec |
| 261 |
|
| 262 |
|
| 263 |
def get_type( |
| 264 |
config_path: str, |
| 265 |
config: Any, |
| 266 |
normalize=True, |
| 267 |
default_type: Optional[Type[Any]] = None, |
| 268 |
): |
| 269 |
"""Gets type of field in config described by a config_path. |
| 270 |
|
| 271 |
Example usage: |
| 272 |
>>> config = {'a': {'b', {'c', 10}}} |
| 273 |
>>> assert config_path.get_type('a.b.c', config) is int |
| 274 |
|
| 275 |
Args: |
| 276 |
config_path: Any string that `split` can process. |
| 277 |
config: A nested datastructure |
| 278 |
normalize: whether to normalize the type (in particular strip Optional |
| 279 |
annotations on dataclass fields) |
| 280 |
default_type: If the `config_path` is not found and `default_type` is set, |
| 281 |
the `default_type` is returned. |
| 282 |
|
| 283 |
Returns: |
| 284 |
The type of last object when walking config with config_path. |
| 285 |
|
| 286 |
Raises: |
| 287 |
IndexError: Integer field not found in nested structure. |
| 288 |
KeyError: Non-integer field not found in nested structure. |
| 289 |
ValueError: Empty/invalid config_path after parsing. |
| 290 |
TypeError: Ambiguous type annotation on dataclass field. |
| 291 |
""" |
| 292 |
holder, field = _get_holder_field(config_path, config) |
| 293 |
|
| 294 |
if isinstance(holder, |
| 295 |
(config_dict.ConfigDict, config_dict.FieldReference)): |
| 296 |
if default_type is not None and field not in holder: |
| 297 |
return default_type |
| 298 |
return holder.get_type(field) |
| 299 |
|
| 300 |
elif dc.is_dataclass(holder): |
| 301 |
matches = [f.type for f in dc.fields(holder) if f.name == field] |
| 302 |
if not matches: |
| 303 |
raise KeyError(f'Field {field} not found on dataclass {type(holder)}') |
| 304 |
return normalize_type(matches[0]) if normalize else matches[0] |
| 305 |
else: |
| 306 |
return type(_get_item_or_attribute(holder, field, config_path)) |
| 307 |
|
| 308 |
|
| 309 |
def is_optional(config_path: str, config: Any) -> bool: |
| 310 |
raw_type = get_type(config_path, config, normalize=False) |
| 311 |
return extract_type_from_optional(raw_type) is not None |
| 312 |
|
| 313 |
|
| 314 |
def set_value( |
| 315 |
config_path: str, |
| 316 |
config: Any, |
| 317 |
value: Any, |
| 318 |
*, |
| 319 |
accept_new_attributes: bool = False, |
| 320 |
): |
| 321 |
"""Sets value of field described by config_path. |
| 322 |
|
| 323 |
Example usage: |
| 324 |
>>> config = {'a': {'b', {'c', 10}}} |
| 325 |
>>> config_path.set_value('a.b.c', config, 20) |
| 326 |
>>> assert config['a']['b']['c'] == 20 |
| 327 |
|
| 328 |
Args: |
| 329 |
config_path: Any string that `split` can process. |
| 330 |
config: A nested datastructure |
| 331 |
value: A value to assign to final field. |
| 332 |
accept_new_attributes: If `True`, the new config attributes can be added |
| 333 |
|
| 334 |
Raises: |
| 335 |
IndexError: Integer field not found in nested structure. |
| 336 |
KeyError: Non-integer field not found in nested structure. |
| 337 |
ValueError: Empty/invalid config_path after parsing. |
| 338 |
""" |
| 339 |
holder, field = _get_holder_field(config_path, config) |
| 340 |
|
| 341 |
if isinstance(field, int) and isinstance(holder, MutableSequence): |
| 342 |
holder[field] = value |
| 343 |
elif hasattr(holder, '__setitem__') and ( |
| 344 |
field in holder or accept_new_attributes |
| 345 |
): |
| 346 |
holder[field] = value |
| 347 |
elif hasattr(holder, str(field)): |
| 348 |
setattr(holder, str(field), value) |
| 349 |
else: |
| 350 |
if isinstance(field, int): |
| 351 |
raise IndexError( |
| 352 |
f'{field} is not a valid index for {type(holder)} ' |
| 353 |
f'(in: {config_path})') |
| 354 |
raise KeyError(f'{field} is not a valid key or attribute of {type(holder)} ' |
| 355 |
f'(in: {config_path})') |