nodes.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import copy
  2. import math
  3. import sys
  4. from abc import abstractmethod
  5. from enum import Enum
  6. from pathlib import Path
  7. from typing import Any, Dict, Optional, Type, Union
  8. from omegaconf._utils import (
  9. ValueKind,
  10. _is_interpolation,
  11. get_type_of,
  12. get_value_kind,
  13. is_primitive_container,
  14. type_str,
  15. )
  16. from omegaconf.base import Box, DictKeyType, Metadata, Node
  17. from omegaconf.errors import ReadonlyConfigError, UnsupportedValueType, ValidationError
  18. class ValueNode(Node):
  19. _val: Any
  20. def __init__(self, parent: Optional[Box], value: Any, metadata: Metadata):
  21. from omegaconf import read_write
  22. super().__init__(parent=parent, metadata=metadata)
  23. with read_write(self):
  24. self._set_value(value) # lgtm [py/init-calls-subclass]
  25. def _value(self) -> Any:
  26. return self._val
  27. def _set_value(self, value: Any, flags: Optional[Dict[str, bool]] = None) -> None:
  28. if self._get_flag("readonly"):
  29. raise ReadonlyConfigError("Cannot set value of read-only config node")
  30. if isinstance(value, str) and get_value_kind(
  31. value, strict_interpolation_validation=True
  32. ) in (
  33. ValueKind.INTERPOLATION,
  34. ValueKind.MANDATORY_MISSING,
  35. ):
  36. self._val = value
  37. else:
  38. self._val = self.validate_and_convert(value)
  39. def _strict_validate_type(self, value: Any) -> None:
  40. ref_type = self._metadata.ref_type
  41. if isinstance(ref_type, type) and type(value) is not ref_type:
  42. type_hint = type_str(self._metadata.type_hint)
  43. raise ValidationError(
  44. f"Value '$VALUE' of type '$VALUE_TYPE' is incompatible with type hint '{type_hint}'"
  45. )
  46. def validate_and_convert(self, value: Any) -> Any:
  47. """
  48. Validates input and converts to canonical form
  49. :param value: input value
  50. :return: converted value ("100" may be converted to 100 for example)
  51. """
  52. if value is None:
  53. if self._is_optional():
  54. return None
  55. ref_type_str = type_str(self._metadata.ref_type)
  56. raise ValidationError(
  57. f"Incompatible value '{value}' for field of type '{ref_type_str}'"
  58. )
  59. # Subclasses can assume that `value` is not None in
  60. # `_validate_and_convert_impl()` and in `_strict_validate_type()`.
  61. if self._get_flag("convert") is False:
  62. self._strict_validate_type(value)
  63. return value
  64. else:
  65. return self._validate_and_convert_impl(value)
  66. @abstractmethod
  67. def _validate_and_convert_impl(self, value: Any) -> Any:
  68. ...
  69. def __str__(self) -> str:
  70. return str(self._val)
  71. def __repr__(self) -> str:
  72. return repr(self._val) if hasattr(self, "_val") else "__INVALID__"
  73. def __eq__(self, other: Any) -> bool:
  74. if isinstance(other, AnyNode):
  75. return self._val == other._val # type: ignore
  76. else:
  77. return self._val == other # type: ignore
  78. def __ne__(self, other: Any) -> bool:
  79. x = self.__eq__(other)
  80. assert x is not NotImplemented
  81. return not x
  82. def __hash__(self) -> int:
  83. return hash(self._val)
  84. def _deepcopy_impl(self, res: Any, memo: Dict[int, Any]) -> None:
  85. res.__dict__["_metadata"] = copy.deepcopy(self._metadata, memo=memo)
  86. # shallow copy for value to support non-copyable value
  87. res.__dict__["_val"] = self._val
  88. # parent is retained, but not copied
  89. res.__dict__["_parent"] = self._parent
  90. def _is_optional(self) -> bool:
  91. return self._metadata.optional
  92. def _is_interpolation(self) -> bool:
  93. return _is_interpolation(self._value())
  94. def _get_full_key(self, key: Optional[Union[DictKeyType, int]]) -> str:
  95. parent = self._get_parent()
  96. if parent is None:
  97. if self._metadata.key is None:
  98. return ""
  99. else:
  100. return str(self._metadata.key)
  101. else:
  102. return parent._get_full_key(self._metadata.key)
  103. class AnyNode(ValueNode):
  104. def __init__(
  105. self,
  106. value: Any = None,
  107. key: Any = None,
  108. parent: Optional[Box] = None,
  109. flags: Optional[Dict[str, bool]] = None,
  110. ):
  111. super().__init__(
  112. parent=parent,
  113. value=value,
  114. metadata=Metadata(
  115. ref_type=Any, object_type=None, key=key, optional=True, flags=flags
  116. ),
  117. )
  118. def _validate_and_convert_impl(self, value: Any) -> Any:
  119. from ._utils import is_primitive_type_annotation
  120. # allow_objects is internal and not an official API. use at your own risk.
  121. # Please be aware that this support is subject to change without notice.
  122. # If this is deemed useful and supportable it may become an official API.
  123. if self._get_flag(
  124. "allow_objects"
  125. ) is not True and not is_primitive_type_annotation(value):
  126. t = get_type_of(value)
  127. raise UnsupportedValueType(
  128. f"Value '{t.__name__}' is not a supported primitive type"
  129. )
  130. return value
  131. def __deepcopy__(self, memo: Dict[int, Any]) -> "AnyNode":
  132. res = AnyNode()
  133. self._deepcopy_impl(res, memo)
  134. return res
  135. class StringNode(ValueNode):
  136. def __init__(
  137. self,
  138. value: Any = None,
  139. key: Any = None,
  140. parent: Optional[Box] = None,
  141. is_optional: bool = True,
  142. flags: Optional[Dict[str, bool]] = None,
  143. ):
  144. super().__init__(
  145. parent=parent,
  146. value=value,
  147. metadata=Metadata(
  148. key=key,
  149. optional=is_optional,
  150. ref_type=str,
  151. object_type=str,
  152. flags=flags,
  153. ),
  154. )
  155. def _validate_and_convert_impl(self, value: Any) -> str:
  156. from omegaconf import OmegaConf
  157. if (
  158. OmegaConf.is_config(value)
  159. or is_primitive_container(value)
  160. or isinstance(value, bytes)
  161. ):
  162. raise ValidationError("Cannot convert '$VALUE_TYPE' to string: '$VALUE'")
  163. return str(value)
  164. def __deepcopy__(self, memo: Dict[int, Any]) -> "StringNode":
  165. res = StringNode()
  166. self._deepcopy_impl(res, memo)
  167. return res
  168. class PathNode(ValueNode):
  169. def __init__(
  170. self,
  171. value: Any = None,
  172. key: Any = None,
  173. parent: Optional[Box] = None,
  174. is_optional: bool = True,
  175. flags: Optional[Dict[str, bool]] = None,
  176. ):
  177. super().__init__(
  178. parent=parent,
  179. value=value,
  180. metadata=Metadata(
  181. key=key,
  182. optional=is_optional,
  183. ref_type=Path,
  184. object_type=Path,
  185. flags=flags,
  186. ),
  187. )
  188. def _strict_validate_type(self, value: Any) -> None:
  189. if not isinstance(value, Path):
  190. raise ValidationError(
  191. "Value '$VALUE' of type '$VALUE_TYPE' is not an instance of 'pathlib.Path'"
  192. )
  193. def _validate_and_convert_impl(self, value: Any) -> Path:
  194. if not isinstance(value, (str, Path)):
  195. raise ValidationError(
  196. "Value '$VALUE' of type '$VALUE_TYPE' could not be converted to Path"
  197. )
  198. return Path(value)
  199. def __deepcopy__(self, memo: Dict[int, Any]) -> "PathNode":
  200. res = PathNode()
  201. self._deepcopy_impl(res, memo)
  202. return res
  203. class IntegerNode(ValueNode):
  204. def __init__(
  205. self,
  206. value: Any = None,
  207. key: Any = None,
  208. parent: Optional[Box] = None,
  209. is_optional: bool = True,
  210. flags: Optional[Dict[str, bool]] = None,
  211. ):
  212. super().__init__(
  213. parent=parent,
  214. value=value,
  215. metadata=Metadata(
  216. key=key,
  217. optional=is_optional,
  218. ref_type=int,
  219. object_type=int,
  220. flags=flags,
  221. ),
  222. )
  223. def _validate_and_convert_impl(self, value: Any) -> int:
  224. try:
  225. if type(value) in (str, int):
  226. val = int(value)
  227. else:
  228. raise ValueError()
  229. except ValueError:
  230. raise ValidationError(
  231. "Value '$VALUE' of type '$VALUE_TYPE' could not be converted to Integer"
  232. )
  233. return val
  234. def __deepcopy__(self, memo: Dict[int, Any]) -> "IntegerNode":
  235. res = IntegerNode()
  236. self._deepcopy_impl(res, memo)
  237. return res
  238. class BytesNode(ValueNode):
  239. def __init__(
  240. self,
  241. value: Any = None,
  242. key: Any = None,
  243. parent: Optional[Box] = None,
  244. is_optional: bool = True,
  245. flags: Optional[Dict[str, bool]] = None,
  246. ):
  247. super().__init__(
  248. parent=parent,
  249. value=value,
  250. metadata=Metadata(
  251. key=key,
  252. optional=is_optional,
  253. ref_type=bytes,
  254. object_type=bytes,
  255. flags=flags,
  256. ),
  257. )
  258. def _validate_and_convert_impl(self, value: Any) -> bytes:
  259. if not isinstance(value, bytes):
  260. raise ValidationError(
  261. "Value '$VALUE' of type '$VALUE_TYPE' is not of type 'bytes'"
  262. )
  263. return value
  264. def __deepcopy__(self, memo: Dict[int, Any]) -> "BytesNode":
  265. res = BytesNode()
  266. self._deepcopy_impl(res, memo)
  267. return res
  268. class FloatNode(ValueNode):
  269. def __init__(
  270. self,
  271. value: Any = None,
  272. key: Any = None,
  273. parent: Optional[Box] = None,
  274. is_optional: bool = True,
  275. flags: Optional[Dict[str, bool]] = None,
  276. ):
  277. super().__init__(
  278. parent=parent,
  279. value=value,
  280. metadata=Metadata(
  281. key=key,
  282. optional=is_optional,
  283. ref_type=float,
  284. object_type=float,
  285. flags=flags,
  286. ),
  287. )
  288. def _validate_and_convert_impl(self, value: Any) -> float:
  289. try:
  290. if type(value) in (float, str, int):
  291. return float(value)
  292. else:
  293. raise ValueError()
  294. except ValueError:
  295. raise ValidationError(
  296. "Value '$VALUE' of type '$VALUE_TYPE' could not be converted to Float"
  297. )
  298. def __eq__(self, other: Any) -> bool:
  299. if isinstance(other, ValueNode):
  300. other_val = other._val
  301. else:
  302. other_val = other
  303. if self._val is None and other is None:
  304. return True
  305. if self._val is None and other is not None:
  306. return False
  307. if self._val is not None and other is None:
  308. return False
  309. nan1 = math.isnan(self._val) if isinstance(self._val, float) else False
  310. nan2 = math.isnan(other_val) if isinstance(other_val, float) else False
  311. return self._val == other_val or (nan1 and nan2)
  312. def __hash__(self) -> int:
  313. return hash(self._val)
  314. def __deepcopy__(self, memo: Dict[int, Any]) -> "FloatNode":
  315. res = FloatNode()
  316. self._deepcopy_impl(res, memo)
  317. return res
  318. class BooleanNode(ValueNode):
  319. def __init__(
  320. self,
  321. value: Any = None,
  322. key: Any = None,
  323. parent: Optional[Box] = None,
  324. is_optional: bool = True,
  325. flags: Optional[Dict[str, bool]] = None,
  326. ):
  327. super().__init__(
  328. parent=parent,
  329. value=value,
  330. metadata=Metadata(
  331. key=key,
  332. optional=is_optional,
  333. ref_type=bool,
  334. object_type=bool,
  335. flags=flags,
  336. ),
  337. )
  338. def _validate_and_convert_impl(self, value: Any) -> bool:
  339. if isinstance(value, bool):
  340. return value
  341. if isinstance(value, int):
  342. return value != 0
  343. elif isinstance(value, str):
  344. try:
  345. return self._validate_and_convert_impl(int(value))
  346. except ValueError as e:
  347. if value.lower() in ("yes", "y", "on", "true"):
  348. return True
  349. elif value.lower() in ("no", "n", "off", "false"):
  350. return False
  351. else:
  352. raise ValidationError(
  353. "Value '$VALUE' is not a valid bool (type $VALUE_TYPE)"
  354. ).with_traceback(sys.exc_info()[2]) from e
  355. else:
  356. raise ValidationError(
  357. "Value '$VALUE' is not a valid bool (type $VALUE_TYPE)"
  358. )
  359. def __deepcopy__(self, memo: Dict[int, Any]) -> "BooleanNode":
  360. res = BooleanNode()
  361. self._deepcopy_impl(res, memo)
  362. return res
  363. class EnumNode(ValueNode): # lgtm [py/missing-equals] : Intentional.
  364. """
  365. NOTE: EnumNode is serialized to yaml as a string ("Color.BLUE"), not as a fully qualified yaml type.
  366. this means serialization to YAML of a typed config (with EnumNode) will not retain the type of the Enum
  367. when loaded.
  368. This is intentional, Please open an issue against OmegaConf if you wish to discuss this decision.
  369. """
  370. def __init__(
  371. self,
  372. enum_type: Type[Enum],
  373. value: Optional[Union[Enum, str]] = None,
  374. key: Any = None,
  375. parent: Optional[Box] = None,
  376. is_optional: bool = True,
  377. flags: Optional[Dict[str, bool]] = None,
  378. ):
  379. if not isinstance(enum_type, type) or not issubclass(enum_type, Enum):
  380. raise ValidationError(
  381. f"EnumNode can only operate on Enum subclasses ({enum_type})"
  382. )
  383. self.fields: Dict[str, str] = {}
  384. self.enum_type: Type[Enum] = enum_type
  385. for name, constant in enum_type.__members__.items():
  386. self.fields[name] = constant.value
  387. super().__init__(
  388. parent=parent,
  389. value=value,
  390. metadata=Metadata(
  391. key=key,
  392. optional=is_optional,
  393. ref_type=enum_type,
  394. object_type=enum_type,
  395. flags=flags,
  396. ),
  397. )
  398. def _strict_validate_type(self, value: Any) -> None:
  399. ref_type = self._metadata.ref_type
  400. if not isinstance(value, ref_type):
  401. type_hint = type_str(self._metadata.type_hint)
  402. raise ValidationError(
  403. f"Value '$VALUE' of type '$VALUE_TYPE' is incompatible with type hint '{type_hint}'"
  404. )
  405. def _validate_and_convert_impl(self, value: Any) -> Enum:
  406. return self.validate_and_convert_to_enum(enum_type=self.enum_type, value=value)
  407. @staticmethod
  408. def validate_and_convert_to_enum(enum_type: Type[Enum], value: Any) -> Enum:
  409. if not isinstance(value, (str, int)) and not isinstance(value, enum_type):
  410. raise ValidationError(
  411. f"Value $VALUE ($VALUE_TYPE) is not a valid input for {enum_type}"
  412. )
  413. if isinstance(value, enum_type):
  414. return value
  415. try:
  416. if isinstance(value, (float, bool)):
  417. raise ValueError
  418. if isinstance(value, int):
  419. return enum_type(value)
  420. if isinstance(value, str):
  421. prefix = f"{enum_type.__name__}."
  422. if value.startswith(prefix):
  423. value = value[len(prefix) :]
  424. return enum_type[value]
  425. assert False
  426. except (ValueError, KeyError) as e:
  427. valid = ", ".join([x for x in enum_type.__members__.keys()])
  428. raise ValidationError(
  429. f"Invalid value '$VALUE', expected one of [{valid}]"
  430. ).with_traceback(sys.exc_info()[2]) from e
  431. def __deepcopy__(self, memo: Dict[int, Any]) -> "EnumNode":
  432. res = EnumNode(enum_type=self.enum_type)
  433. self._deepcopy_impl(res, memo)
  434. return res
  435. class InterpolationResultNode(ValueNode):
  436. """
  437. Special node type, used to wrap interpolation results.
  438. """
  439. def __init__(
  440. self,
  441. value: Any,
  442. key: Any = None,
  443. parent: Optional[Box] = None,
  444. flags: Optional[Dict[str, bool]] = None,
  445. ):
  446. super().__init__(
  447. parent=parent,
  448. value=value,
  449. metadata=Metadata(
  450. ref_type=Any, object_type=None, key=key, optional=True, flags=flags
  451. ),
  452. )
  453. # In general we should not try to write into interpolation results.
  454. if flags is None or "readonly" not in flags:
  455. self._set_flag("readonly", True)
  456. def _set_value(self, value: Any, flags: Optional[Dict[str, bool]] = None) -> None:
  457. if self._get_flag("readonly"):
  458. raise ReadonlyConfigError("Cannot set value of read-only config node")
  459. self._val = self.validate_and_convert(value)
  460. def _validate_and_convert_impl(self, value: Any) -> Any:
  461. # Interpolation results may be anything.
  462. return value
  463. def __deepcopy__(self, memo: Dict[int, Any]) -> "InterpolationResultNode":
  464. # Currently there should be no need to deep-copy such nodes.
  465. raise NotImplementedError
  466. def _is_interpolation(self) -> bool:
  467. # The result of an interpolation cannot be itself an interpolation.
  468. return False