Upload 53 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- LICENSE +29 -0
- MANIFEST.in +3 -0
- PKG-INFO +42 -0
- README.md +24 -0
- omegaconf.egg-info/PKG-INFO +42 -0
- omegaconf.egg-info/SOURCES.txt +52 -0
- omegaconf.egg-info/dependency_links.txt +1 -0
- omegaconf.egg-info/requires.txt +5 -0
- omegaconf.egg-info/top_level.txt +1 -0
- omegaconf/__init__.py +58 -0
- omegaconf/_utils.py +772 -0
- omegaconf/base.py +430 -0
- omegaconf/basecontainer.py +626 -0
- omegaconf/dictconfig.py +579 -0
- omegaconf/errors.py +105 -0
- omegaconf/listconfig.py +544 -0
- omegaconf/nodes.py +397 -0
- omegaconf/omegaconf.py +813 -0
- omegaconf/py.typed +0 -0
- omegaconf/version.py +13 -0
- pyproject.toml +35 -0
- requirements/base.txt +4 -0
- setup.cfg +11 -0
- setup.py +65 -0
- tests/__init__.py +156 -0
- tests/conftest.py +18 -0
- tests/examples/__init__.py +0 -0
- tests/examples/test_dataclass_example.py +381 -0
- tests/structured_conf/__init__.py +0 -0
- tests/structured_conf/data/__init__.py +0 -0
- tests/structured_conf/data/attr_classes.py +472 -0
- tests/structured_conf/data/dataclasses.py +484 -0
- tests/structured_conf/test_structured_basic.py +201 -0
- tests/structured_conf/test_structured_config.py +983 -0
- tests/test_base_config.py +586 -0
- tests/test_basic_ops_dict.py +737 -0
- tests/test_basic_ops_list.py +591 -0
- tests/test_config_eq.py +165 -0
- tests/test_create.py +150 -0
- tests/test_errors.py +1098 -0
- tests/test_get_full_key.py +116 -0
- tests/test_interpolation.py +433 -0
- tests/test_matrix.py +379 -0
- tests/test_merge.py +524 -0
- tests/test_nodes.py +552 -0
- tests/test_omegaconf.py +379 -0
- tests/test_readonly.py +230 -0
- tests/test_select.py +88 -0
- tests/test_serialization.py +208 -0
- tests/test_struct.py +60 -0
LICENSE
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
BSD 3-Clause License
|
2 |
+
|
3 |
+
Copyright (c) 2018, Omry Yadan
|
4 |
+
All rights reserved.
|
5 |
+
|
6 |
+
Redistribution and use in source and binary forms, with or without
|
7 |
+
modification, are permitted provided that the following conditions are met:
|
8 |
+
|
9 |
+
1. Redistributions of source code must retain the above copyright notice, this
|
10 |
+
list of conditions and the following disclaimer.
|
11 |
+
|
12 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
13 |
+
this list of conditions and the following disclaimer in the documentation
|
14 |
+
and/or other materials provided with the distribution.
|
15 |
+
|
16 |
+
3. Neither the name of the copyright holder nor the names of its
|
17 |
+
contributors may be used to endorse or promote products derived from
|
18 |
+
this software without specific prior written permission.
|
19 |
+
|
20 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
21 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
22 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
23 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
24 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
25 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
26 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
27 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
28 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
29 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
MANIFEST.in
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
include LICENSE
|
2 |
+
include requirements/base.txt
|
3 |
+
recursive-include tests *.py
|
PKG-INFO
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: omegaconf
|
3 |
+
Version: 2.0.6
|
4 |
+
Summary: A flexible configuration library
|
5 |
+
Home-page: https://github.com/omry/omegaconf
|
6 |
+
Author: Omry Yadan
|
7 |
+
Author-email: [email protected]
|
8 |
+
License: UNKNOWN
|
9 |
+
Description: # OmegaConf
|
10 |
+
| | Description |
|
11 |
+
| --- | --- |
|
12 |
+
| Project | [![PyPI version](https://badge.fury.io/py/omegaconf.svg)](https://badge.fury.io/py/omegaconf)[![Downloads](https://pepy.tech/badge/omegaconf/month)](https://pepy.tech/project/omegaconf/month?versions=1.4.*&versions=2.0*)![PyPI - Python Version](https://img.shields.io/pypi/pyversions/omegaconf.svg) |
|
13 |
+
| Code quality| [![CircleCI](https://img.shields.io/circleci/build/github/omry/omegaconf?logo=s&token=5de2f8dc2a0dd78438520575431aa533150806e3)](https://circleci.com/gh/omry/omegaconf)[![Coverage Status](https://coveralls.io/repos/github/omry/omegaconf/badge.svg)](https://coveralls.io/github/omry/omegaconf)[![Total alerts](https://img.shields.io/lgtm/alerts/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/alerts/)[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/context:python)|
|
14 |
+
| Docs and support |[![Documentation Status](https://readthedocs.org/projects/omegaconf/badge/?version=2.0_branch)](https://omegaconf.readthedocs.io/en/latest/?badge=2.0_branch)[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)[![](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://hydra-framework.zulipchat.com)|
|
15 |
+
|
16 |
+
|
17 |
+
OmegaConf is a hierarchical configuration system, with support for merging configurations from multiple sources (YAML config files, dataclasses/objects and CLI arguments)
|
18 |
+
providing a consistent API regardless of how the configuration was created.
|
19 |
+
|
20 |
+
## Releases
|
21 |
+
### Stable (2.0)
|
22 |
+
OmegaConf 2.0 stable version.
|
23 |
+
|
24 |
+
* [What's new](https://github.com/omry/omegaconf/releases/tag/2.0.0)
|
25 |
+
* [Documentation](https://omegaconf.readthedocs.io/en/2.0_branch/)
|
26 |
+
* [Slides](https://docs.google.com/presentation/d/e/2PACX-1vT_UIV7hCnquIbLUm4NnkUpXvPEh33IKiUEvPRF850WKA8opOlZOszjKdZ3tPmf8u7hGNP6HpqS-NT5/pub?start=false&loop=false&delayms=3000)
|
27 |
+
* [Source code](https://github.com/omry/omegaconf/tree/2.0_branch)
|
28 |
+
|
29 |
+
Install with `pip install --upgrade omegaconf`
|
30 |
+
|
31 |
+
## Live tutorial
|
32 |
+
Run the live tutorial : [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)
|
33 |
+
|
34 |
+
Keywords: yaml configuration config
|
35 |
+
Platform: UNKNOWN
|
36 |
+
Classifier: Programming Language :: Python :: 3.6
|
37 |
+
Classifier: Programming Language :: Python :: 3.7
|
38 |
+
Classifier: Programming Language :: Python :: 3.8
|
39 |
+
Classifier: License :: OSI Approved :: BSD License
|
40 |
+
Classifier: Operating System :: OS Independent
|
41 |
+
Requires-Python: >=3.6
|
42 |
+
Description-Content-Type: text/markdown
|
README.md
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# OmegaConf
|
2 |
+
| | Description |
|
3 |
+
| --- | --- |
|
4 |
+
| Project | [![PyPI version](https://badge.fury.io/py/omegaconf.svg)](https://badge.fury.io/py/omegaconf)[![Downloads](https://pepy.tech/badge/omegaconf/month)](https://pepy.tech/project/omegaconf/month?versions=1.4.*&versions=2.0*)![PyPI - Python Version](https://img.shields.io/pypi/pyversions/omegaconf.svg) |
|
5 |
+
| Code quality| [![CircleCI](https://img.shields.io/circleci/build/github/omry/omegaconf?logo=s&token=5de2f8dc2a0dd78438520575431aa533150806e3)](https://circleci.com/gh/omry/omegaconf)[![Coverage Status](https://coveralls.io/repos/github/omry/omegaconf/badge.svg)](https://coveralls.io/github/omry/omegaconf)[![Total alerts](https://img.shields.io/lgtm/alerts/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/alerts/)[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/context:python)|
|
6 |
+
| Docs and support |[![Documentation Status](https://readthedocs.org/projects/omegaconf/badge/?version=2.0_branch)](https://omegaconf.readthedocs.io/en/latest/?badge=2.0_branch)[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)[![](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://hydra-framework.zulipchat.com)|
|
7 |
+
|
8 |
+
|
9 |
+
OmegaConf is a hierarchical configuration system, with support for merging configurations from multiple sources (YAML config files, dataclasses/objects and CLI arguments)
|
10 |
+
providing a consistent API regardless of how the configuration was created.
|
11 |
+
|
12 |
+
## Releases
|
13 |
+
### Stable (2.0)
|
14 |
+
OmegaConf 2.0 stable version.
|
15 |
+
|
16 |
+
* [What's new](https://github.com/omry/omegaconf/releases/tag/2.0.0)
|
17 |
+
* [Documentation](https://omegaconf.readthedocs.io/en/2.0_branch/)
|
18 |
+
* [Slides](https://docs.google.com/presentation/d/e/2PACX-1vT_UIV7hCnquIbLUm4NnkUpXvPEh33IKiUEvPRF850WKA8opOlZOszjKdZ3tPmf8u7hGNP6HpqS-NT5/pub?start=false&loop=false&delayms=3000)
|
19 |
+
* [Source code](https://github.com/omry/omegaconf/tree/2.0_branch)
|
20 |
+
|
21 |
+
Install with `pip install --upgrade omegaconf`
|
22 |
+
|
23 |
+
## Live tutorial
|
24 |
+
Run the live tutorial : [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)
|
omegaconf.egg-info/PKG-INFO
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: omegaconf
|
3 |
+
Version: 2.0.6
|
4 |
+
Summary: A flexible configuration library
|
5 |
+
Home-page: https://github.com/omry/omegaconf
|
6 |
+
Author: Omry Yadan
|
7 |
+
Author-email: [email protected]
|
8 |
+
License: UNKNOWN
|
9 |
+
Description: # OmegaConf
|
10 |
+
| | Description |
|
11 |
+
| --- | --- |
|
12 |
+
| Project | [![PyPI version](https://badge.fury.io/py/omegaconf.svg)](https://badge.fury.io/py/omegaconf)[![Downloads](https://pepy.tech/badge/omegaconf/month)](https://pepy.tech/project/omegaconf/month?versions=1.4.*&versions=2.0*)![PyPI - Python Version](https://img.shields.io/pypi/pyversions/omegaconf.svg) |
|
13 |
+
| Code quality| [![CircleCI](https://img.shields.io/circleci/build/github/omry/omegaconf?logo=s&token=5de2f8dc2a0dd78438520575431aa533150806e3)](https://circleci.com/gh/omry/omegaconf)[![Coverage Status](https://coveralls.io/repos/github/omry/omegaconf/badge.svg)](https://coveralls.io/github/omry/omegaconf)[![Total alerts](https://img.shields.io/lgtm/alerts/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/alerts/)[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/context:python)|
|
14 |
+
| Docs and support |[![Documentation Status](https://readthedocs.org/projects/omegaconf/badge/?version=2.0_branch)](https://omegaconf.readthedocs.io/en/latest/?badge=2.0_branch)[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)[![](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://hydra-framework.zulipchat.com)|
|
15 |
+
|
16 |
+
|
17 |
+
OmegaConf is a hierarchical configuration system, with support for merging configurations from multiple sources (YAML config files, dataclasses/objects and CLI arguments)
|
18 |
+
providing a consistent API regardless of how the configuration was created.
|
19 |
+
|
20 |
+
## Releases
|
21 |
+
### Stable (2.0)
|
22 |
+
OmegaConf 2.0 stable version.
|
23 |
+
|
24 |
+
* [What's new](https://github.com/omry/omegaconf/releases/tag/2.0.0)
|
25 |
+
* [Documentation](https://omegaconf.readthedocs.io/en/2.0_branch/)
|
26 |
+
* [Slides](https://docs.google.com/presentation/d/e/2PACX-1vT_UIV7hCnquIbLUm4NnkUpXvPEh33IKiUEvPRF850WKA8opOlZOszjKdZ3tPmf8u7hGNP6HpqS-NT5/pub?start=false&loop=false&delayms=3000)
|
27 |
+
* [Source code](https://github.com/omry/omegaconf/tree/2.0_branch)
|
28 |
+
|
29 |
+
Install with `pip install --upgrade omegaconf`
|
30 |
+
|
31 |
+
## Live tutorial
|
32 |
+
Run the live tutorial : [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)
|
33 |
+
|
34 |
+
Keywords: yaml configuration config
|
35 |
+
Platform: UNKNOWN
|
36 |
+
Classifier: Programming Language :: Python :: 3.6
|
37 |
+
Classifier: Programming Language :: Python :: 3.7
|
38 |
+
Classifier: Programming Language :: Python :: 3.8
|
39 |
+
Classifier: License :: OSI Approved :: BSD License
|
40 |
+
Classifier: Operating System :: OS Independent
|
41 |
+
Requires-Python: >=3.6
|
42 |
+
Description-Content-Type: text/markdown
|
omegaconf.egg-info/SOURCES.txt
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
LICENSE
|
2 |
+
MANIFEST.in
|
3 |
+
README.md
|
4 |
+
pyproject.toml
|
5 |
+
setup.cfg
|
6 |
+
setup.py
|
7 |
+
omegaconf/__init__.py
|
8 |
+
omegaconf/_utils.py
|
9 |
+
omegaconf/base.py
|
10 |
+
omegaconf/basecontainer.py
|
11 |
+
omegaconf/dictconfig.py
|
12 |
+
omegaconf/errors.py
|
13 |
+
omegaconf/listconfig.py
|
14 |
+
omegaconf/nodes.py
|
15 |
+
omegaconf/omegaconf.py
|
16 |
+
omegaconf/py.typed
|
17 |
+
omegaconf/version.py
|
18 |
+
omegaconf.egg-info/PKG-INFO
|
19 |
+
omegaconf.egg-info/SOURCES.txt
|
20 |
+
omegaconf.egg-info/dependency_links.txt
|
21 |
+
omegaconf.egg-info/requires.txt
|
22 |
+
omegaconf.egg-info/top_level.txt
|
23 |
+
requirements/base.txt
|
24 |
+
tests/__init__.py
|
25 |
+
tests/conftest.py
|
26 |
+
tests/test_base_config.py
|
27 |
+
tests/test_basic_ops_dict.py
|
28 |
+
tests/test_basic_ops_list.py
|
29 |
+
tests/test_config_eq.py
|
30 |
+
tests/test_create.py
|
31 |
+
tests/test_errors.py
|
32 |
+
tests/test_get_full_key.py
|
33 |
+
tests/test_interpolation.py
|
34 |
+
tests/test_matrix.py
|
35 |
+
tests/test_merge.py
|
36 |
+
tests/test_nodes.py
|
37 |
+
tests/test_omegaconf.py
|
38 |
+
tests/test_readonly.py
|
39 |
+
tests/test_select.py
|
40 |
+
tests/test_serialization.py
|
41 |
+
tests/test_struct.py
|
42 |
+
tests/test_to_yaml.py
|
43 |
+
tests/test_update.py
|
44 |
+
tests/test_utils.py
|
45 |
+
tests/examples/__init__.py
|
46 |
+
tests/examples/test_dataclass_example.py
|
47 |
+
tests/structured_conf/__init__.py
|
48 |
+
tests/structured_conf/test_structured_basic.py
|
49 |
+
tests/structured_conf/test_structured_config.py
|
50 |
+
tests/structured_conf/data/__init__.py
|
51 |
+
tests/structured_conf/data/attr_classes.py
|
52 |
+
tests/structured_conf/data/dataclasses.py
|
omegaconf.egg-info/dependency_links.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
omegaconf.egg-info/requires.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
PyYAML>=5.1.*
|
2 |
+
typing-extensions
|
3 |
+
|
4 |
+
[:python_version == "3.6"]
|
5 |
+
dataclasses
|
omegaconf.egg-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
omegaconf
|
omegaconf/__init__.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .base import Container, Node
|
2 |
+
from .dictconfig import DictConfig
|
3 |
+
from .errors import (
|
4 |
+
KeyValidationError,
|
5 |
+
MissingMandatoryValue,
|
6 |
+
ReadonlyConfigError,
|
7 |
+
UnsupportedValueType,
|
8 |
+
ValidationError,
|
9 |
+
)
|
10 |
+
from .listconfig import ListConfig
|
11 |
+
from .nodes import (
|
12 |
+
AnyNode,
|
13 |
+
BooleanNode,
|
14 |
+
EnumNode,
|
15 |
+
FloatNode,
|
16 |
+
IntegerNode,
|
17 |
+
StringNode,
|
18 |
+
ValueNode,
|
19 |
+
)
|
20 |
+
from .omegaconf import (
|
21 |
+
II,
|
22 |
+
MISSING,
|
23 |
+
SI,
|
24 |
+
OmegaConf,
|
25 |
+
Resolver,
|
26 |
+
flag_override,
|
27 |
+
open_dict,
|
28 |
+
read_write,
|
29 |
+
)
|
30 |
+
from .version import __version__
|
31 |
+
|
32 |
+
__all__ = [
|
33 |
+
"__version__",
|
34 |
+
"MissingMandatoryValue",
|
35 |
+
"ValidationError",
|
36 |
+
"ReadonlyConfigError",
|
37 |
+
"UnsupportedValueType",
|
38 |
+
"KeyValidationError",
|
39 |
+
"Container",
|
40 |
+
"ListConfig",
|
41 |
+
"DictConfig",
|
42 |
+
"OmegaConf",
|
43 |
+
"Resolver",
|
44 |
+
"flag_override",
|
45 |
+
"read_write",
|
46 |
+
"open_dict",
|
47 |
+
"Node",
|
48 |
+
"ValueNode",
|
49 |
+
"AnyNode",
|
50 |
+
"IntegerNode",
|
51 |
+
"StringNode",
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
import string
|
5 |
+
import sys
|
6 |
+
import warnings
|
7 |
+
from enum import Enum
|
8 |
+
from textwrap import dedent
|
9 |
+
from typing import Any, Dict, List, Match, Optional, Tuple, Type, Union
|
10 |
+
|
11 |
+
import yaml
|
12 |
+
|
13 |
+
from .errors import (
|
14 |
+
ConfigIndexError,
|
15 |
+
ConfigTypeError,
|
16 |
+
ConfigValueError,
|
17 |
+
KeyValidationError,
|
18 |
+
OmegaConfBaseException,
|
19 |
+
ValidationError,
|
20 |
+
)
|
21 |
+
|
22 |
+
try:
|
23 |
+
import dataclasses
|
24 |
+
|
25 |
+
except ImportError: # pragma: no cover
|
26 |
+
dataclasses = None # type: ignore # pragma: no cover
|
27 |
+
|
28 |
+
try:
|
29 |
+
import attr
|
30 |
+
|
31 |
+
except ImportError: # pragma: no cover
|
32 |
+
attr = None # type: ignore # pragma: no cover
|
33 |
+
|
34 |
+
|
35 |
+
# source: https://yaml.org/type/bool.html
|
36 |
+
YAML_BOOL_TYPES = [
|
37 |
+
"y",
|
38 |
+
"Y",
|
39 |
+
"yes",
|
40 |
+
"Yes",
|
41 |
+
"YES",
|
42 |
+
"n",
|
43 |
+
"N",
|
44 |
+
"no",
|
45 |
+
"No",
|
46 |
+
"NO",
|
47 |
+
"true",
|
48 |
+
"True",
|
49 |
+
"TRUE",
|
50 |
+
"false",
|
51 |
+
"False",
|
52 |
+
"FALSE",
|
53 |
+
"on",
|
54 |
+
"On",
|
55 |
+
"ON",
|
56 |
+
"off",
|
57 |
+
"Off",
|
58 |
+
"OFF",
|
59 |
+
]
|
60 |
+
|
61 |
+
|
62 |
+
class OmegaConfDumper(yaml.Dumper): # type: ignore
|
63 |
+
str_representer_added = False
|
64 |
+
|
65 |
+
@staticmethod
|
66 |
+
def str_representer(dumper: yaml.Dumper, data: str) -> yaml.ScalarNode:
|
67 |
+
with_quotes = yaml_is_bool(data) or is_int(data) or is_float(data)
|
68 |
+
return dumper.represent_scalar(
|
69 |
+
yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG,
|
70 |
+
data,
|
71 |
+
style=("'" if with_quotes else None),
|
72 |
+
)
|
73 |
+
|
74 |
+
|
75 |
+
def get_omega_conf_dumper() -> Type[OmegaConfDumper]:
|
76 |
+
if not OmegaConfDumper.str_representer_added:
|
77 |
+
OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer)
|
78 |
+
OmegaConfDumper.str_representer_added = True
|
79 |
+
return OmegaConfDumper
|
80 |
+
|
81 |
+
|
82 |
+
def yaml_is_bool(b: str) -> bool:
|
83 |
+
return b in YAML_BOOL_TYPES
|
84 |
+
|
85 |
+
|
86 |
+
def get_yaml_loader() -> Any:
|
87 |
+
# Custom constructor that checks for duplicate keys
|
88 |
+
# (from https://gist.github.com/pypt/94d747fe5180851196eb)
|
89 |
+
def no_duplicates_constructor(
|
90 |
+
loader: yaml.Loader, node: yaml.Node, deep: bool = False
|
91 |
+
) -> Any:
|
92 |
+
mapping: Dict[str, Any] = {}
|
93 |
+
for key_node, value_node in node.value:
|
94 |
+
key = loader.construct_object(key_node, deep=deep)
|
95 |
+
value = loader.construct_object(value_node, deep=deep)
|
96 |
+
if key in mapping:
|
97 |
+
raise yaml.constructor.ConstructorError(
|
98 |
+
"while constructing a mapping",
|
99 |
+
node.start_mark,
|
100 |
+
f"found duplicate key {key}",
|
101 |
+
key_node.start_mark,
|
102 |
+
)
|
103 |
+
mapping[key] = value
|
104 |
+
return loader.construct_mapping(node, deep)
|
105 |
+
|
106 |
+
class OmegaConfLoader(yaml.SafeLoader): # type: ignore
|
107 |
+
pass
|
108 |
+
|
109 |
+
loader = OmegaConfLoader
|
110 |
+
loader.add_implicit_resolver(
|
111 |
+
"tag:yaml.org,2002:float",
|
112 |
+
re.compile(
|
113 |
+
"""^(?:
|
114 |
+
[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
|
115 |
+
|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
|
116 |
+
|\\.[0-9_]+(?:[eE][-+][0-9]+)?
|
117 |
+
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
|
118 |
+
|[-+]?\\.(?:inf|Inf|INF)
|
119 |
+
|\\.(?:nan|NaN|NAN))$""",
|
120 |
+
re.X,
|
121 |
+
),
|
122 |
+
list("-+0123456789."),
|
123 |
+
) # type : ignore
|
124 |
+
loader.yaml_implicit_resolvers = {
|
125 |
+
key: [
|
126 |
+
(tag, regexp)
|
127 |
+
for tag, regexp in resolvers
|
128 |
+
if tag != "tag:yaml.org,2002:timestamp"
|
129 |
+
]
|
130 |
+
for key, resolvers in loader.yaml_implicit_resolvers.items()
|
131 |
+
}
|
132 |
+
loader.add_constructor(
|
133 |
+
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, no_duplicates_constructor
|
134 |
+
)
|
135 |
+
return loader
|
136 |
+
|
137 |
+
|
138 |
+
def _get_class(path: str) -> type:
|
139 |
+
from importlib import import_module
|
140 |
+
|
141 |
+
module_path, _, class_name = path.rpartition(".")
|
142 |
+
mod = import_module(module_path)
|
143 |
+
try:
|
144 |
+
klass: type = getattr(mod, class_name)
|
145 |
+
except AttributeError:
|
146 |
+
raise ImportError(f"Class {class_name} is not in module {module_path}")
|
147 |
+
return klass
|
148 |
+
|
149 |
+
|
150 |
+
def _is_union(type_: Any) -> bool:
|
151 |
+
return getattr(type_, "__origin__", None) is Union
|
152 |
+
|
153 |
+
|
154 |
+
def _resolve_optional(type_: Any) -> Tuple[bool, Any]:
|
155 |
+
if getattr(type_, "__origin__", None) is Union:
|
156 |
+
args = type_.__args__
|
157 |
+
if len(args) == 2 and args[1] == type(None): # noqa E721
|
158 |
+
return True, args[0]
|
159 |
+
if type_ is Any:
|
160 |
+
return True, Any
|
161 |
+
|
162 |
+
return False, type_
|
163 |
+
|
164 |
+
|
165 |
+
def _resolve_forward(type_: Type[Any], module: str) -> Type[Any]:
|
166 |
+
import typing # lgtm [py/import-and-import-from]
|
167 |
+
|
168 |
+
forward = typing.ForwardRef if hasattr(typing, "ForwardRef") else typing._ForwardRef # type: ignore
|
169 |
+
if type(type_) is forward:
|
170 |
+
return _get_class(f"{module}.{type_.__forward_arg__}")
|
171 |
+
else:
|
172 |
+
return type_
|
173 |
+
|
174 |
+
|
175 |
+
def _raise_missing_error(obj: Any, name: str) -> None:
|
176 |
+
raise ValueError(
|
177 |
+
f"Missing default value for {get_type_of(obj).__name__}.{name}, to indicate "
|
178 |
+
"default must be populated later use OmegaConf.MISSING"
|
179 |
+
)
|
180 |
+
|
181 |
+
|
182 |
+
def get_attr_data(obj: Any) -> Dict[str, Any]:
|
183 |
+
from omegaconf.omegaconf import _maybe_wrap
|
184 |
+
|
185 |
+
d = {}
|
186 |
+
is_type = isinstance(obj, type)
|
187 |
+
obj_type = obj if is_type else type(obj)
|
188 |
+
for name, attrib in attr.fields_dict(obj_type).items():
|
189 |
+
is_optional, type_ = _resolve_optional(attrib.type)
|
190 |
+
is_nested = is_attr_class(type_)
|
191 |
+
type_ = _resolve_forward(type_, obj.__module__)
|
192 |
+
if not is_type:
|
193 |
+
value = getattr(obj, name)
|
194 |
+
else:
|
195 |
+
value = attrib.default
|
196 |
+
if value == attr.NOTHING:
|
197 |
+
if is_nested:
|
198 |
+
msg = dedent(
|
199 |
+
f"""
|
200 |
+
The field `{name}` of type '{type_str(type_)}' does not have a default value.
|
201 |
+
The behavior of OmegaConf for such cases is changing in OmegaConf 2.1.
|
202 |
+
See https://github.com/omry/omegaconf/issues/412 for more details.
|
203 |
+
"""
|
204 |
+
)
|
205 |
+
warnings.warn(category=UserWarning, message=msg, stacklevel=8)
|
206 |
+
value = type_
|
207 |
+
else:
|
208 |
+
_raise_missing_error(obj, name)
|
209 |
+
assert False
|
210 |
+
if _is_union(type_):
|
211 |
+
e = ConfigValueError(
|
212 |
+
f"Union types are not supported:\n{name}: {type_str(type_)}"
|
213 |
+
)
|
214 |
+
format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e))
|
215 |
+
|
216 |
+
d[name] = _maybe_wrap(
|
217 |
+
ref_type=type_, is_optional=is_optional, key=name, value=value, parent=None
|
218 |
+
)
|
219 |
+
return d
|
220 |
+
|
221 |
+
|
222 |
+
def get_dataclass_data(obj: Any) -> Dict[str, Any]:
|
223 |
+
from omegaconf.omegaconf import _maybe_wrap
|
224 |
+
|
225 |
+
d = {}
|
226 |
+
for field in dataclasses.fields(obj):
|
227 |
+
name = field.name
|
228 |
+
is_optional, type_ = _resolve_optional(field.type)
|
229 |
+
type_ = _resolve_forward(type_, obj.__module__)
|
230 |
+
is_nested = is_structured_config(type_)
|
231 |
+
|
232 |
+
if hasattr(obj, name):
|
233 |
+
value = getattr(obj, name)
|
234 |
+
if value == dataclasses.MISSING:
|
235 |
+
_raise_missing_error(obj, name)
|
236 |
+
assert False
|
237 |
+
else:
|
238 |
+
if field.default_factory == dataclasses.MISSING: # type: ignore
|
239 |
+
if is_nested:
|
240 |
+
msg = dedent(
|
241 |
+
f"""
|
242 |
+
The field `{name}` of type '{type_str(type_)}' does not have a default value.
|
243 |
+
The behavior of OmegaConf for such cases is changing in OmegaConf 2.1.
|
244 |
+
See https://github.com/omry/omegaconf/issues/412 for more details.
|
245 |
+
"""
|
246 |
+
)
|
247 |
+
warnings.warn(category=UserWarning, message=msg, stacklevel=8)
|
248 |
+
|
249 |
+
value = type_
|
250 |
+
else:
|
251 |
+
_raise_missing_error(obj, name)
|
252 |
+
assert False
|
253 |
+
else:
|
254 |
+
value = field.default_factory() # type: ignore
|
255 |
+
|
256 |
+
if _is_union(type_):
|
257 |
+
e = ConfigValueError(
|
258 |
+
f"Union types are not supported:\n{name}: {type_str(type_)}"
|
259 |
+
)
|
260 |
+
format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e))
|
261 |
+
d[name] = _maybe_wrap(
|
262 |
+
ref_type=type_, is_optional=is_optional, key=name, value=value, parent=None
|
263 |
+
)
|
264 |
+
return d
|
265 |
+
|
266 |
+
|
267 |
+
def is_dataclass(obj: Any) -> bool:
|
268 |
+
from omegaconf.base import Node
|
269 |
+
|
270 |
+
if dataclasses is None or isinstance(obj, Node):
|
271 |
+
return False
|
272 |
+
return dataclasses.is_dataclass(obj)
|
273 |
+
|
274 |
+
|
275 |
+
def is_attr_class(obj: Any) -> bool:
|
276 |
+
from omegaconf.base import Node
|
277 |
+
|
278 |
+
if attr is None or isinstance(obj, Node):
|
279 |
+
return False
|
280 |
+
return attr.has(obj)
|
281 |
+
|
282 |
+
|
283 |
+
def is_structured_config(obj: Any) -> bool:
|
284 |
+
return is_attr_class(obj) or is_dataclass(obj)
|
285 |
+
|
286 |
+
|
287 |
+
def is_dataclass_frozen(type_: Any) -> bool:
|
288 |
+
return type_.__dataclass_params__.frozen # type: ignore
|
289 |
+
|
290 |
+
|
291 |
+
def is_attr_frozen(type_: type) -> bool:
|
292 |
+
# This is very hacky and probably fragile as well.
|
293 |
+
# Unfortunately currently there isn't an official API in attr that can detect that.
|
294 |
+
# noinspection PyProtectedMember
|
295 |
+
return type_.__setattr__ == attr._make._frozen_setattrs # type: ignore
|
296 |
+
|
297 |
+
|
298 |
+
def get_type_of(class_or_object: Any) -> Type[Any]:
|
299 |
+
type_ = class_or_object
|
300 |
+
if not isinstance(type_, type):
|
301 |
+
type_ = type(class_or_object)
|
302 |
+
assert isinstance(type_, type)
|
303 |
+
return type_
|
304 |
+
|
305 |
+
|
306 |
+
def is_structured_config_frozen(obj: Any) -> bool:
|
307 |
+
type_ = get_type_of(obj)
|
308 |
+
|
309 |
+
if is_dataclass(type_):
|
310 |
+
return is_dataclass_frozen(type_)
|
311 |
+
if is_attr_class(type_):
|
312 |
+
return is_attr_frozen(type_)
|
313 |
+
return False
|
314 |
+
|
315 |
+
|
316 |
+
def get_structured_config_data(obj: Any) -> Dict[str, Any]:
|
317 |
+
if is_dataclass(obj):
|
318 |
+
return get_dataclass_data(obj)
|
319 |
+
elif is_attr_class(obj):
|
320 |
+
return get_attr_data(obj)
|
321 |
+
else:
|
322 |
+
raise ValueError(f"Unsupported type: {type(obj).__name__}")
|
323 |
+
|
324 |
+
|
325 |
+
class ValueKind(Enum):
|
326 |
+
VALUE = 0
|
327 |
+
MANDATORY_MISSING = 1
|
328 |
+
INTERPOLATION = 2
|
329 |
+
STR_INTERPOLATION = 3
|
330 |
+
|
331 |
+
|
332 |
+
def get_value_kind(value: Any, return_match_list: bool = False) -> Any:
|
333 |
+
"""
|
334 |
+
Determine the kind of a value
|
335 |
+
Examples:
|
336 |
+
MANDATORY_MISSING : "???
|
337 |
+
VALUE : "10", "20", True,
|
338 |
+
INTERPOLATION: "${foo}", "${foo.bar}"
|
339 |
+
STR_INTERPOLATION: "ftp://${host}/path"
|
340 |
+
|
341 |
+
:param value: input string to classify
|
342 |
+
:param return_match_list: True to return the match list as well
|
343 |
+
:return: ValueKind
|
344 |
+
"""
|
345 |
+
|
346 |
+
key_prefix = r"\${(\w+:)?"
|
347 |
+
legal_characters = r"([\w\.%_ \\/:,-]*?)}"
|
348 |
+
match_list: Optional[List[Match[str]]] = None
|
349 |
+
|
350 |
+
def ret(
|
351 |
+
value_kind: ValueKind,
|
352 |
+
) -> Union[ValueKind, Tuple[ValueKind, Optional[List[Match[str]]]]]:
|
353 |
+
if return_match_list:
|
354 |
+
return value_kind, match_list
|
355 |
+
else:
|
356 |
+
return value_kind
|
357 |
+
|
358 |
+
from .base import Container
|
359 |
+
|
360 |
+
if isinstance(value, Container):
|
361 |
+
if value._is_interpolation() or value._is_missing():
|
362 |
+
value = value._value()
|
363 |
+
|
364 |
+
value = _get_value(value)
|
365 |
+
if value == "???":
|
366 |
+
return ret(ValueKind.MANDATORY_MISSING)
|
367 |
+
|
368 |
+
if not isinstance(value, str):
|
369 |
+
return ret(ValueKind.VALUE)
|
370 |
+
|
371 |
+
match_list = list(re.finditer(key_prefix + legal_characters, value))
|
372 |
+
if len(match_list) == 0:
|
373 |
+
return ret(ValueKind.VALUE)
|
374 |
+
|
375 |
+
if len(match_list) == 1 and value == match_list[0].group(0):
|
376 |
+
return ret(ValueKind.INTERPOLATION)
|
377 |
+
else:
|
378 |
+
return ret(ValueKind.STR_INTERPOLATION)
|
379 |
+
|
380 |
+
|
381 |
+
def is_bool(st: str) -> bool:
|
382 |
+
st = str.lower(st)
|
383 |
+
return st == "true" or st == "false"
|
384 |
+
|
385 |
+
|
386 |
+
def is_float(st: str) -> bool:
|
387 |
+
try:
|
388 |
+
float(st)
|
389 |
+
return True
|
390 |
+
except ValueError:
|
391 |
+
return False
|
392 |
+
|
393 |
+
|
394 |
+
def is_int(st: str) -> bool:
|
395 |
+
try:
|
396 |
+
int(st)
|
397 |
+
return True
|
398 |
+
except ValueError:
|
399 |
+
return False
|
400 |
+
|
401 |
+
|
402 |
+
def decode_primitive(s: str) -> Any:
|
403 |
+
if is_bool(s):
|
404 |
+
return str.lower(s) == "true"
|
405 |
+
|
406 |
+
if is_int(s):
|
407 |
+
return int(s)
|
408 |
+
|
409 |
+
if is_float(s):
|
410 |
+
return float(s)
|
411 |
+
|
412 |
+
return s
|
413 |
+
|
414 |
+
|
415 |
+
def is_primitive_list(obj: Any) -> bool:
|
416 |
+
from .base import Container
|
417 |
+
|
418 |
+
return not isinstance(obj, Container) and isinstance(obj, (list, tuple))
|
419 |
+
|
420 |
+
|
421 |
+
def is_primitive_dict(obj: Any) -> bool:
|
422 |
+
t = get_type_of(obj)
|
423 |
+
return t is dict
|
424 |
+
|
425 |
+
|
426 |
+
def is_dict_annotation(type_: Any) -> bool:
|
427 |
+
origin = getattr(type_, "__origin__", None)
|
428 |
+
if sys.version_info < (3, 7, 0):
|
429 |
+
return origin is Dict or type_ is Dict # pragma: no cover
|
430 |
+
else:
|
431 |
+
return origin is dict # pragma: no cover
|
432 |
+
|
433 |
+
|
434 |
+
def is_list_annotation(type_: Any) -> bool:
|
435 |
+
origin = getattr(type_, "__origin__", None)
|
436 |
+
if sys.version_info < (3, 7, 0):
|
437 |
+
return origin is List or type_ is List # pragma: no cover
|
438 |
+
else:
|
439 |
+
return origin is list # pragma: no cover
|
440 |
+
|
441 |
+
|
442 |
+
def is_tuple_annotation(type_: Any) -> bool:
|
443 |
+
origin = getattr(type_, "__origin__", None)
|
444 |
+
if sys.version_info < (3, 7, 0):
|
445 |
+
return origin is Tuple or type_ is Tuple # pragma: no cover
|
446 |
+
else:
|
447 |
+
return origin is tuple # pragma: no cover
|
448 |
+
|
449 |
+
|
450 |
+
def is_dict_subclass(type_: Any) -> bool:
|
451 |
+
return type_ is not None and isinstance(type_, type) and issubclass(type_, Dict)
|
452 |
+
|
453 |
+
|
454 |
+
def is_dict(obj: Any) -> bool:
|
455 |
+
return is_primitive_dict(obj) or is_dict_annotation(obj) or is_dict_subclass(obj)
|
456 |
+
|
457 |
+
|
458 |
+
def is_primitive_container(obj: Any) -> bool:
|
459 |
+
return is_primitive_list(obj) or is_primitive_dict(obj)
|
460 |
+
|
461 |
+
|
462 |
+
def get_list_element_type(ref_type: Optional[Type[Any]]) -> Optional[Type[Any]]:
|
463 |
+
args = getattr(ref_type, "__args__", None)
|
464 |
+
if ref_type is not List and args is not None and args[0] is not Any:
|
465 |
+
element_type = args[0]
|
466 |
+
else:
|
467 |
+
element_type = None
|
468 |
+
|
469 |
+
if not (valid_value_annotation_type(element_type)):
|
470 |
+
raise ValidationError(f"Unsupported value type : {element_type}")
|
471 |
+
assert element_type is None or isinstance(element_type, type)
|
472 |
+
return element_type
|
473 |
+
|
474 |
+
|
475 |
+
def get_dict_key_value_types(ref_type: Any) -> Tuple[Any, Any]:
|
476 |
+
|
477 |
+
args = getattr(ref_type, "__args__", None)
|
478 |
+
if args is None:
|
479 |
+
bases = getattr(ref_type, "__orig_bases__", None)
|
480 |
+
if bases is not None and len(bases) > 0:
|
481 |
+
args = getattr(bases[0], "__args__", None)
|
482 |
+
|
483 |
+
key_type: Any
|
484 |
+
element_type: Any
|
485 |
+
if ref_type is None:
|
486 |
+
key_type = None
|
487 |
+
element_type = None
|
488 |
+
else:
|
489 |
+
if args is not None:
|
490 |
+
key_type = args[0]
|
491 |
+
element_type = args[1]
|
492 |
+
# None is the sentry for any type
|
493 |
+
if key_type is Any:
|
494 |
+
key_type = None
|
495 |
+
if element_type is Any:
|
496 |
+
element_type = None
|
497 |
+
else:
|
498 |
+
key_type = None
|
499 |
+
element_type = None
|
500 |
+
|
501 |
+
if not valid_value_annotation_type(element_type) and not is_structured_config(
|
502 |
+
element_type
|
503 |
+
):
|
504 |
+
raise ValidationError(f"Unsupported value type : {element_type}")
|
505 |
+
|
506 |
+
if not _valid_dict_key_annotation_type(key_type):
|
507 |
+
raise KeyValidationError(f"Unsupported key type {key_type}")
|
508 |
+
return key_type, element_type
|
509 |
+
|
510 |
+
|
511 |
+
def valid_value_annotation_type(type_: Any) -> bool:
|
512 |
+
return type_ is Any or is_primitive_type(type_) or is_structured_config(type_)
|
513 |
+
|
514 |
+
|
515 |
+
def _valid_dict_key_annotation_type(type_: Any) -> bool:
|
516 |
+
return type_ is None or issubclass(type_, str) or issubclass(type_, Enum)
|
517 |
+
|
518 |
+
|
519 |
+
def is_primitive_type(type_: Any) -> bool:
|
520 |
+
type_ = get_type_of(type_)
|
521 |
+
return issubclass(type_, Enum) or type_ in (int, float, bool, str, type(None))
|
522 |
+
|
523 |
+
|
524 |
+
def _is_interpolation(v: Any) -> bool:
|
525 |
+
if isinstance(v, str):
|
526 |
+
ret = get_value_kind(v) in (
|
527 |
+
ValueKind.INTERPOLATION,
|
528 |
+
ValueKind.STR_INTERPOLATION,
|
529 |
+
)
|
530 |
+
assert isinstance(ret, bool)
|
531 |
+
return ret
|
532 |
+
return False
|
533 |
+
|
534 |
+
|
535 |
+
def _get_value(value: Any) -> Any:
|
536 |
+
from .base import Container
|
537 |
+
from .nodes import ValueNode
|
538 |
+
|
539 |
+
if isinstance(value, Container) and value._is_none():
|
540 |
+
return None
|
541 |
+
if isinstance(value, ValueNode):
|
542 |
+
value = value._value()
|
543 |
+
return value
|
544 |
+
|
545 |
+
|
546 |
+
def get_ref_type(obj: Any, key: Any = None) -> Optional[Type[Any]]:
|
547 |
+
from omegaconf import DictConfig, ListConfig
|
548 |
+
from omegaconf.base import Container, Node
|
549 |
+
from omegaconf.nodes import ValueNode
|
550 |
+
|
551 |
+
def none_as_any(t: Optional[Type[Any]]) -> Union[Type[Any], Any]:
|
552 |
+
if t is None:
|
553 |
+
return Any
|
554 |
+
else:
|
555 |
+
return t
|
556 |
+
|
557 |
+
if isinstance(obj, Container) and key is not None:
|
558 |
+
obj = obj._get_node(key)
|
559 |
+
|
560 |
+
is_optional = True
|
561 |
+
ref_type = None
|
562 |
+
if isinstance(obj, ValueNode):
|
563 |
+
is_optional = obj._is_optional()
|
564 |
+
ref_type = obj._metadata.ref_type
|
565 |
+
elif isinstance(obj, Container):
|
566 |
+
if isinstance(obj, Node):
|
567 |
+
ref_type = obj._metadata.ref_type
|
568 |
+
is_optional = obj._is_optional()
|
569 |
+
kt = none_as_any(obj._metadata.key_type)
|
570 |
+
vt = none_as_any(obj._metadata.element_type)
|
571 |
+
if (
|
572 |
+
ref_type is Any
|
573 |
+
and kt is Any
|
574 |
+
and vt is Any
|
575 |
+
and not obj._is_missing()
|
576 |
+
and not obj._is_none()
|
577 |
+
):
|
578 |
+
ref_type = Any # type: ignore
|
579 |
+
elif not is_structured_config(ref_type):
|
580 |
+
if kt is Any:
|
581 |
+
kt = Union[str, Enum]
|
582 |
+
if isinstance(obj, DictConfig):
|
583 |
+
ref_type = Dict[kt, vt] # type: ignore
|
584 |
+
elif isinstance(obj, ListConfig):
|
585 |
+
ref_type = List[vt] # type: ignore
|
586 |
+
else:
|
587 |
+
if isinstance(obj, dict):
|
588 |
+
ref_type = Dict[Union[str, Enum], Any]
|
589 |
+
elif isinstance(obj, (list, tuple)):
|
590 |
+
ref_type = List[Any]
|
591 |
+
else:
|
592 |
+
ref_type = get_type_of(obj)
|
593 |
+
|
594 |
+
ref_type = none_as_any(ref_type)
|
595 |
+
if is_optional and ref_type is not Any:
|
596 |
+
ref_type = Optional[ref_type] # type: ignore
|
597 |
+
return ref_type
|
598 |
+
|
599 |
+
|
600 |
+
def _raise(ex: Exception, cause: Exception) -> None:
|
601 |
+
# Set the environment variable OC_CAUSE=1 to get a stacktrace that includes the
|
602 |
+
# causing exception.
|
603 |
+
env_var = os.environ["OC_CAUSE"] if "OC_CAUSE" in os.environ else None
|
604 |
+
debugging = sys.gettrace() is not None
|
605 |
+
full_backtrace = (debugging and not env_var == "0") or (env_var == "1")
|
606 |
+
if full_backtrace:
|
607 |
+
ex.__cause__ = cause
|
608 |
+
else:
|
609 |
+
ex.__cause__ = None
|
610 |
+
raise ex # set end OC_CAUSE=1 for full backtrace
|
611 |
+
|
612 |
+
|
613 |
+
def format_and_raise(
|
614 |
+
node: Any,
|
615 |
+
key: Any,
|
616 |
+
value: Any,
|
617 |
+
msg: str,
|
618 |
+
cause: Exception,
|
619 |
+
type_override: Any = None,
|
620 |
+
) -> None:
|
621 |
+
from omegaconf import OmegaConf
|
622 |
+
from omegaconf.base import Node
|
623 |
+
|
624 |
+
if isinstance(cause, OmegaConfBaseException) and cause._initialized:
|
625 |
+
ex = cause
|
626 |
+
if type_override is not None:
|
627 |
+
ex = type_override(str(cause))
|
628 |
+
ex.__dict__ = copy.deepcopy(cause.__dict__)
|
629 |
+
_raise(ex, cause)
|
630 |
+
|
631 |
+
object_type: Optional[Type[Any]]
|
632 |
+
object_type_str: Optional[str] = None
|
633 |
+
ref_type: Optional[Type[Any]]
|
634 |
+
ref_type_str: Optional[str]
|
635 |
+
|
636 |
+
child_node: Optional[Node] = None
|
637 |
+
if node is None:
|
638 |
+
full_key = ""
|
639 |
+
object_type = None
|
640 |
+
ref_type = None
|
641 |
+
ref_type_str = None
|
642 |
+
else:
|
643 |
+
if key is not None and not OmegaConf.is_none(node):
|
644 |
+
child_node = node._get_node(key, validate_access=False)
|
645 |
+
|
646 |
+
full_key = node._get_full_key(key=key)
|
647 |
+
|
648 |
+
object_type = OmegaConf.get_type(node)
|
649 |
+
object_type_str = type_str(object_type)
|
650 |
+
|
651 |
+
ref_type = get_ref_type(node)
|
652 |
+
ref_type_str = type_str(ref_type)
|
653 |
+
|
654 |
+
msg = string.Template(msg).substitute(
|
655 |
+
REF_TYPE=ref_type_str,
|
656 |
+
OBJECT_TYPE=object_type_str,
|
657 |
+
KEY=key,
|
658 |
+
FULL_KEY=full_key,
|
659 |
+
VALUE=value,
|
660 |
+
VALUE_TYPE=f"{type(value).__name__}",
|
661 |
+
KEY_TYPE=f"{type(key).__name__}",
|
662 |
+
)
|
663 |
+
|
664 |
+
template = """$MSG
|
665 |
+
\tfull_key: $FULL_KEY
|
666 |
+
\treference_type=$REF_TYPE
|
667 |
+
\tobject_type=$OBJECT_TYPE"""
|
668 |
+
|
669 |
+
s = string.Template(template=template)
|
670 |
+
|
671 |
+
message = s.substitute(
|
672 |
+
REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key
|
673 |
+
)
|
674 |
+
exception_type = type(cause) if type_override is None else type_override
|
675 |
+
if exception_type == TypeError:
|
676 |
+
exception_type = ConfigTypeError
|
677 |
+
elif exception_type == IndexError:
|
678 |
+
exception_type = ConfigIndexError
|
679 |
+
|
680 |
+
ex = exception_type(f"{message}")
|
681 |
+
if issubclass(exception_type, OmegaConfBaseException):
|
682 |
+
ex._initialized = True
|
683 |
+
ex.msg = message
|
684 |
+
ex.parent_node = node
|
685 |
+
ex.child_node = child_node
|
686 |
+
ex.key = key
|
687 |
+
ex.full_key = full_key
|
688 |
+
ex.value = value
|
689 |
+
ex.object_type = object_type
|
690 |
+
ex.object_type_str = object_type_str
|
691 |
+
ex.ref_type = ref_type
|
692 |
+
ex.ref_type_str = ref_type_str
|
693 |
+
|
694 |
+
_raise(ex, cause)
|
695 |
+
|
696 |
+
|
697 |
+
def type_str(t: Any) -> str:
|
698 |
+
is_optional, t = _resolve_optional(t)
|
699 |
+
if t is None:
|
700 |
+
return type(t).__name__
|
701 |
+
if t is Any:
|
702 |
+
return "Any"
|
703 |
+
if sys.version_info < (3, 7, 0): # pragma: no cover
|
704 |
+
# Python 3.6
|
705 |
+
if hasattr(t, "__name__"):
|
706 |
+
name = str(t.__name__)
|
707 |
+
else:
|
708 |
+
if t.__origin__ is not None:
|
709 |
+
name = type_str(t.__origin__)
|
710 |
+
else:
|
711 |
+
name = str(t)
|
712 |
+
if name.startswith("typing."):
|
713 |
+
name = name[len("typing.") :]
|
714 |
+
else: # pragma: no cover
|
715 |
+
# Python >= 3.7
|
716 |
+
if hasattr(t, "__name__"):
|
717 |
+
name = str(t.__name__)
|
718 |
+
else:
|
719 |
+
if t._name is None:
|
720 |
+
if t.__origin__ is not None:
|
721 |
+
name = type_str(t.__origin__)
|
722 |
+
else:
|
723 |
+
name = str(t._name)
|
724 |
+
|
725 |
+
args = getattr(t, "__args__", None)
|
726 |
+
if args is not None:
|
727 |
+
args = ", ".join([type_str(t) for t in (list(t.__args__))])
|
728 |
+
ret = f"{name}[{args}]"
|
729 |
+
else:
|
730 |
+
ret = name
|
731 |
+
if is_optional:
|
732 |
+
return f"Optional[{ret}]"
|
733 |
+
else:
|
734 |
+
return ret
|
735 |
+
|
736 |
+
|
737 |
+
def _ensure_container(target: Any) -> Any:
|
738 |
+
from omegaconf import OmegaConf
|
739 |
+
|
740 |
+
if is_primitive_container(target):
|
741 |
+
assert isinstance(target, (list, dict))
|
742 |
+
target = OmegaConf.create(target)
|
743 |
+
elif is_structured_config(target):
|
744 |
+
target = OmegaConf.structured(target)
|
745 |
+
assert OmegaConf.is_config(target)
|
746 |
+
return target
|
747 |
+
|
748 |
+
|
749 |
+
def is_generic_list(type_: Any) -> bool:
|
750 |
+
"""
|
751 |
+
Checks if a type is a generic list, for example:
|
752 |
+
list returns False
|
753 |
+
typing.List returns False
|
754 |
+
typing.List[T] returns True
|
755 |
+
|
756 |
+
:param type_: variable type
|
757 |
+
:return: bool
|
758 |
+
"""
|
759 |
+
return is_list_annotation(type_) and get_list_element_type(type_) is not None
|
760 |
+
|
761 |
+
|
762 |
+
def is_generic_dict(type_: Any) -> bool:
|
763 |
+
"""
|
764 |
+
Checks if a type is a generic dict, for example:
|
765 |
+
list returns False
|
766 |
+
typing.List returns False
|
767 |
+
typing.List[T] returns True
|
768 |
+
|
769 |
+
:param type_: variable type
|
770 |
+
:return: bool
|
771 |
+
"""
|
772 |
+
return is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) > 0
|
omegaconf/base.py
ADDED
@@ -0,0 +1,430 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import ABC, abstractmethod
|
2 |
+
from collections import defaultdict
|
3 |
+
from dataclasses import dataclass, field
|
4 |
+
from enum import Enum
|
5 |
+
from typing import Any, Dict, Iterator, Optional, Tuple, Type, Union
|
6 |
+
|
7 |
+
from ._utils import ValueKind, _get_value, format_and_raise, get_value_kind
|
8 |
+
from .errors import ConfigKeyError, MissingMandatoryValue, UnsupportedInterpolationType
|
9 |
+
|
10 |
+
|
11 |
+
@dataclass
|
12 |
+
class Metadata:
|
13 |
+
|
14 |
+
ref_type: Optional[Type[Any]]
|
15 |
+
|
16 |
+
object_type: Optional[Type[Any]]
|
17 |
+
|
18 |
+
optional: bool
|
19 |
+
|
20 |
+
key: Any
|
21 |
+
|
22 |
+
# Flags have 3 modes:
|
23 |
+
# unset : inherit from parent (None if no parent specifies)
|
24 |
+
# set to true: flag is true
|
25 |
+
# set to false: flag is false
|
26 |
+
flags: Dict[str, bool] = field(default_factory=dict)
|
27 |
+
resolver_cache: Dict[str, Any] = field(default_factory=lambda: defaultdict(dict))
|
28 |
+
|
29 |
+
|
30 |
+
@dataclass
|
31 |
+
class ContainerMetadata(Metadata):
|
32 |
+
key_type: Any = None
|
33 |
+
element_type: Any = None
|
34 |
+
|
35 |
+
def __post_init__(self) -> None:
|
36 |
+
assert self.key_type is None or isinstance(self.key_type, type)
|
37 |
+
assert self.element_type is None or isinstance(self.element_type, type)
|
38 |
+
|
39 |
+
|
40 |
+
class Node(ABC):
|
41 |
+
_metadata: Metadata
|
42 |
+
|
43 |
+
parent: Optional["Container"]
|
44 |
+
|
45 |
+
def __init__(self, parent: Optional["Container"], metadata: Metadata):
|
46 |
+
self.__dict__["_metadata"] = metadata
|
47 |
+
self.__dict__["_parent"] = parent
|
48 |
+
|
49 |
+
def _set_parent(self, parent: Optional["Container"]) -> None:
|
50 |
+
assert parent is None or isinstance(parent, Container)
|
51 |
+
self.__dict__["_parent"] = parent
|
52 |
+
|
53 |
+
def _get_parent(self) -> Optional["Container"]:
|
54 |
+
parent = self.__dict__["_parent"]
|
55 |
+
assert parent is None or isinstance(parent, Container)
|
56 |
+
return parent
|
57 |
+
|
58 |
+
def _set_flag(self, flag: str, value: Optional[bool]) -> "Node":
|
59 |
+
assert value is None or isinstance(value, bool)
|
60 |
+
if value is None:
|
61 |
+
if flag in self._metadata.flags:
|
62 |
+
del self._metadata.flags[flag]
|
63 |
+
else:
|
64 |
+
self._metadata.flags[flag] = value
|
65 |
+
return self
|
66 |
+
|
67 |
+
def _get_node_flag(self, flag: str) -> Optional[bool]:
|
68 |
+
"""
|
69 |
+
:param flag: flag to inspect
|
70 |
+
:return: the state of the flag on this node.
|
71 |
+
"""
|
72 |
+
return self._metadata.flags[flag] if flag in self._metadata.flags else None
|
73 |
+
|
74 |
+
def _get_flag(self, flag: str) -> Optional[bool]:
|
75 |
+
"""
|
76 |
+
Returns True if this config node flag is set
|
77 |
+
A flag is set if node.set_flag(True) was called
|
78 |
+
or one if it's parents is flag is set
|
79 |
+
:return:
|
80 |
+
"""
|
81 |
+
flags = self._metadata.flags
|
82 |
+
if flag in flags and flags[flag] is not None:
|
83 |
+
return flags[flag]
|
84 |
+
|
85 |
+
parent = self._get_parent()
|
86 |
+
if parent is None:
|
87 |
+
return None
|
88 |
+
else:
|
89 |
+
# noinspection PyProtectedMember
|
90 |
+
return parent._get_flag(flag)
|
91 |
+
|
92 |
+
def _format_and_raise(
|
93 |
+
self, key: Any, value: Any, cause: Exception, type_override: Any = None
|
94 |
+
) -> None:
|
95 |
+
format_and_raise(
|
96 |
+
node=self,
|
97 |
+
key=key,
|
98 |
+
value=value,
|
99 |
+
msg=str(cause),
|
100 |
+
cause=cause,
|
101 |
+
type_override=type_override,
|
102 |
+
)
|
103 |
+
assert False
|
104 |
+
|
105 |
+
@abstractmethod
|
106 |
+
def _get_full_key(self, key: Union[str, Enum, int, None]) -> str:
|
107 |
+
...
|
108 |
+
|
109 |
+
def _dereference_node(
|
110 |
+
self, throw_on_missing: bool = False, throw_on_resolution_failure: bool = True
|
111 |
+
) -> Optional["Node"]:
|
112 |
+
from .nodes import StringNode
|
113 |
+
|
114 |
+
if self._is_interpolation():
|
115 |
+
value_kind, match_list = get_value_kind(
|
116 |
+
value=self._value(), return_match_list=True
|
117 |
+
)
|
118 |
+
match = match_list[0]
|
119 |
+
parent = self._get_parent()
|
120 |
+
key = self._key()
|
121 |
+
if value_kind == ValueKind.INTERPOLATION:
|
122 |
+
assert parent is not None
|
123 |
+
v = parent._resolve_simple_interpolation(
|
124 |
+
key=key,
|
125 |
+
inter_type=match.group(1),
|
126 |
+
inter_key=match.group(2),
|
127 |
+
throw_on_missing=throw_on_missing,
|
128 |
+
throw_on_resolution_failure=throw_on_resolution_failure,
|
129 |
+
)
|
130 |
+
return v
|
131 |
+
elif value_kind == ValueKind.STR_INTERPOLATION:
|
132 |
+
assert parent is not None
|
133 |
+
ret = parent._resolve_interpolation(
|
134 |
+
key=key,
|
135 |
+
value=self,
|
136 |
+
throw_on_missing=throw_on_missing,
|
137 |
+
throw_on_resolution_failure=throw_on_resolution_failure,
|
138 |
+
)
|
139 |
+
if ret is None:
|
140 |
+
return ret
|
141 |
+
return StringNode(
|
142 |
+
value=ret,
|
143 |
+
key=key,
|
144 |
+
parent=parent,
|
145 |
+
is_optional=self._metadata.optional,
|
146 |
+
)
|
147 |
+
assert False
|
148 |
+
else:
|
149 |
+
# not interpolation, compare directly
|
150 |
+
if throw_on_missing:
|
151 |
+
value = self._value()
|
152 |
+
if value == "???":
|
153 |
+
raise MissingMandatoryValue("Missing mandatory value")
|
154 |
+
return self
|
155 |
+
|
156 |
+
@abstractmethod
|
157 |
+
def __eq__(self, other: Any) -> bool:
|
158 |
+
...
|
159 |
+
|
160 |
+
@abstractmethod
|
161 |
+
def __ne__(self, other: Any) -> bool:
|
162 |
+
...
|
163 |
+
|
164 |
+
@abstractmethod
|
165 |
+
def __hash__(self) -> int:
|
166 |
+
...
|
167 |
+
|
168 |
+
@abstractmethod
|
169 |
+
def _value(self) -> Any:
|
170 |
+
...
|
171 |
+
|
172 |
+
@abstractmethod
|
173 |
+
def _set_value(self, value: Any) -> None:
|
174 |
+
...
|
175 |
+
|
176 |
+
@abstractmethod
|
177 |
+
def _is_none(self) -> bool:
|
178 |
+
...
|
179 |
+
|
180 |
+
@abstractmethod
|
181 |
+
def _is_optional(self) -> bool:
|
182 |
+
...
|
183 |
+
|
184 |
+
@abstractmethod
|
185 |
+
def _is_missing(self) -> bool:
|
186 |
+
...
|
187 |
+
|
188 |
+
@abstractmethod
|
189 |
+
def _is_interpolation(self) -> bool:
|
190 |
+
...
|
191 |
+
|
192 |
+
def _key(self) -> Any:
|
193 |
+
return self._metadata.key
|
194 |
+
|
195 |
+
def _set_key(self, key: Any) -> None:
|
196 |
+
self._metadata.key = key
|
197 |
+
|
198 |
+
|
199 |
+
class Container(Node):
|
200 |
+
"""
|
201 |
+
Container tagging interface
|
202 |
+
"""
|
203 |
+
|
204 |
+
_metadata: ContainerMetadata
|
205 |
+
|
206 |
+
@abstractmethod
|
207 |
+
def pretty(self, resolve: bool = False, sort_keys: bool = False) -> str:
|
208 |
+
...
|
209 |
+
|
210 |
+
@abstractmethod
|
211 |
+
def update_node(self, key: str, value: Any = None) -> None:
|
212 |
+
...
|
213 |
+
|
214 |
+
@abstractmethod
|
215 |
+
def select(self, key: str, throw_on_missing: bool = False) -> Any:
|
216 |
+
...
|
217 |
+
|
218 |
+
def _get_node(self, key: Any, validate_access: bool = True) -> Optional[Node]:
|
219 |
+
...
|
220 |
+
|
221 |
+
@abstractmethod
|
222 |
+
def __delitem__(self, key: Any) -> None:
|
223 |
+
...
|
224 |
+
|
225 |
+
@abstractmethod
|
226 |
+
def __setitem__(self, key: Any, value: Any) -> None:
|
227 |
+
...
|
228 |
+
|
229 |
+
@abstractmethod
|
230 |
+
def __iter__(self) -> Iterator[str]:
|
231 |
+
...
|
232 |
+
|
233 |
+
@abstractmethod
|
234 |
+
def __getitem__(self, key_or_index: Any) -> Any:
|
235 |
+
...
|
236 |
+
|
237 |
+
def _get_root(self) -> "Container":
|
238 |
+
root: Optional[Container] = self._get_parent()
|
239 |
+
if root is None:
|
240 |
+
return self
|
241 |
+
assert root is not None and isinstance(root, Container)
|
242 |
+
while root._get_parent() is not None:
|
243 |
+
root = root._get_parent()
|
244 |
+
assert root is not None and isinstance(root, Container)
|
245 |
+
return root
|
246 |
+
|
247 |
+
def _select_impl(
|
248 |
+
self, key: str, throw_on_missing: bool, throw_on_resolution_failure: bool
|
249 |
+
) -> Tuple[Optional["Container"], Optional[str], Optional[Node]]:
|
250 |
+
"""
|
251 |
+
Select a value using dot separated key sequence
|
252 |
+
:param key:
|
253 |
+
:return:
|
254 |
+
"""
|
255 |
+
from .omegaconf import _select_one
|
256 |
+
|
257 |
+
if key == "":
|
258 |
+
return self, "", self
|
259 |
+
|
260 |
+
split = key.split(".")
|
261 |
+
root: Optional[Container] = self
|
262 |
+
for i in range(len(split) - 1):
|
263 |
+
if root is None:
|
264 |
+
break
|
265 |
+
|
266 |
+
k = split[i]
|
267 |
+
ret, _ = _select_one(
|
268 |
+
c=root,
|
269 |
+
key=k,
|
270 |
+
throw_on_missing=throw_on_missing,
|
271 |
+
throw_on_type_error=throw_on_resolution_failure,
|
272 |
+
)
|
273 |
+
if isinstance(ret, Node):
|
274 |
+
ret = ret._dereference_node(
|
275 |
+
throw_on_missing=throw_on_missing,
|
276 |
+
throw_on_resolution_failure=throw_on_resolution_failure,
|
277 |
+
)
|
278 |
+
|
279 |
+
assert ret is None or isinstance(ret, Container)
|
280 |
+
root = ret
|
281 |
+
|
282 |
+
if root is None:
|
283 |
+
return None, None, None
|
284 |
+
|
285 |
+
last_key = split[-1]
|
286 |
+
value, _ = _select_one(
|
287 |
+
c=root,
|
288 |
+
key=last_key,
|
289 |
+
throw_on_missing=throw_on_missing,
|
290 |
+
throw_on_type_error=throw_on_resolution_failure,
|
291 |
+
)
|
292 |
+
if value is None:
|
293 |
+
return root, last_key, value
|
294 |
+
value = root._resolve_interpolation(
|
295 |
+
key=last_key,
|
296 |
+
value=value,
|
297 |
+
throw_on_missing=False,
|
298 |
+
throw_on_resolution_failure=True,
|
299 |
+
)
|
300 |
+
return root, last_key, value
|
301 |
+
|
302 |
+
def _resolve_simple_interpolation(
|
303 |
+
self,
|
304 |
+
key: Any,
|
305 |
+
inter_type: str,
|
306 |
+
inter_key: str,
|
307 |
+
throw_on_missing: bool,
|
308 |
+
throw_on_resolution_failure: bool,
|
309 |
+
) -> Optional["Node"]:
|
310 |
+
from omegaconf import OmegaConf
|
311 |
+
|
312 |
+
from .nodes import ValueNode
|
313 |
+
|
314 |
+
root_node = self._get_root()
|
315 |
+
|
316 |
+
inter_type = ("str:" if inter_type is None else inter_type)[0:-1]
|
317 |
+
if inter_type == "str":
|
318 |
+
parent, last_key, value = root_node._select_impl(
|
319 |
+
inter_key,
|
320 |
+
throw_on_missing=throw_on_missing,
|
321 |
+
throw_on_resolution_failure=throw_on_resolution_failure,
|
322 |
+
)
|
323 |
+
|
324 |
+
# if parent is None or (value is None and last_key not in parent): # type: ignore
|
325 |
+
if parent is None or value is None:
|
326 |
+
if throw_on_resolution_failure:
|
327 |
+
raise ConfigKeyError(
|
328 |
+
f"{inter_type} interpolation key '{inter_key}' not found"
|
329 |
+
)
|
330 |
+
else:
|
331 |
+
return None
|
332 |
+
assert isinstance(value, Node)
|
333 |
+
return value
|
334 |
+
else:
|
335 |
+
resolver = OmegaConf.get_resolver(inter_type)
|
336 |
+
if resolver is not None:
|
337 |
+
try:
|
338 |
+
value = resolver(root_node, inter_key)
|
339 |
+
return ValueNode(
|
340 |
+
value=value,
|
341 |
+
parent=self,
|
342 |
+
metadata=Metadata(
|
343 |
+
ref_type=None, object_type=None, key=key, optional=True
|
344 |
+
),
|
345 |
+
)
|
346 |
+
except Exception as e:
|
347 |
+
self._format_and_raise(key=inter_key, value=None, cause=e)
|
348 |
+
assert False
|
349 |
+
else:
|
350 |
+
if throw_on_resolution_failure:
|
351 |
+
raise UnsupportedInterpolationType(
|
352 |
+
f"Unsupported interpolation type {inter_type}"
|
353 |
+
)
|
354 |
+
else:
|
355 |
+
return None
|
356 |
+
|
357 |
+
def _resolve_interpolation(
|
358 |
+
self,
|
359 |
+
key: Any,
|
360 |
+
value: "Node",
|
361 |
+
throw_on_missing: bool,
|
362 |
+
throw_on_resolution_failure: bool,
|
363 |
+
) -> Any:
|
364 |
+
from .nodes import StringNode
|
365 |
+
|
366 |
+
value_kind, match_list = get_value_kind(value=value, return_match_list=True)
|
367 |
+
if value_kind not in (ValueKind.INTERPOLATION, ValueKind.STR_INTERPOLATION):
|
368 |
+
return value
|
369 |
+
|
370 |
+
if value_kind == ValueKind.INTERPOLATION:
|
371 |
+
# simple interpolation, inherit type
|
372 |
+
match = match_list[0]
|
373 |
+
return self._resolve_simple_interpolation(
|
374 |
+
key=key,
|
375 |
+
inter_type=match.group(1),
|
376 |
+
inter_key=match.group(2),
|
377 |
+
throw_on_missing=throw_on_missing,
|
378 |
+
throw_on_resolution_failure=throw_on_resolution_failure,
|
379 |
+
)
|
380 |
+
elif value_kind == ValueKind.STR_INTERPOLATION:
|
381 |
+
value = _get_value(value)
|
382 |
+
assert isinstance(value, str)
|
383 |
+
orig = value
|
384 |
+
new = ""
|
385 |
+
last_index = 0
|
386 |
+
for match in match_list:
|
387 |
+
new_val = self._resolve_simple_interpolation(
|
388 |
+
key=key,
|
389 |
+
inter_type=match.group(1),
|
390 |
+
inter_key=match.group(2),
|
391 |
+
throw_on_missing=throw_on_missing,
|
392 |
+
throw_on_resolution_failure=throw_on_resolution_failure,
|
393 |
+
)
|
394 |
+
# if failed to resolve, return None for the whole thing.
|
395 |
+
if new_val is None:
|
396 |
+
return None
|
397 |
+
new += orig[last_index : match.start(0)] + str(new_val)
|
398 |
+
last_index = match.end(0)
|
399 |
+
|
400 |
+
new += orig[last_index:]
|
401 |
+
return StringNode(value=new, key=key)
|
402 |
+
else:
|
403 |
+
assert False
|
404 |
+
|
405 |
+
def _re_parent(self) -> None:
|
406 |
+
from .dictconfig import DictConfig
|
407 |
+
from .listconfig import ListConfig
|
408 |
+
|
409 |
+
# update parents of first level Config nodes to self
|
410 |
+
|
411 |
+
if isinstance(self, Container):
|
412 |
+
if isinstance(self, DictConfig):
|
413 |
+
content = self.__dict__["_content"]
|
414 |
+
if isinstance(content, dict):
|
415 |
+
for _key, value in self.__dict__["_content"].items():
|
416 |
+
if value is not None:
|
417 |
+
value._set_parent(self)
|
418 |
+
if isinstance(value, Container):
|
419 |
+
value._re_parent()
|
420 |
+
elif isinstance(self, ListConfig):
|
421 |
+
content = self.__dict__["_content"]
|
422 |
+
if isinstance(content, list):
|
423 |
+
for item in self.__dict__["_content"]:
|
424 |
+
if item is not None:
|
425 |
+
item._set_parent(self)
|
426 |
+
if isinstance(item, Container):
|
427 |
+
item._re_parent()
|
428 |
+
|
429 |
+
def _has_ref_type(self) -> bool:
|
430 |
+
return self._metadata.ref_type is not Any
|
omegaconf/basecontainer.py
ADDED
@@ -0,0 +1,626 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import sys
|
3 |
+
import warnings
|
4 |
+
from abc import ABC, abstractmethod
|
5 |
+
from enum import Enum
|
6 |
+
from textwrap import dedent
|
7 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
8 |
+
|
9 |
+
import yaml
|
10 |
+
|
11 |
+
from ._utils import (
|
12 |
+
ValueKind,
|
13 |
+
_ensure_container,
|
14 |
+
_get_value,
|
15 |
+
_is_interpolation,
|
16 |
+
_resolve_optional,
|
17 |
+
get_ref_type,
|
18 |
+
get_value_kind,
|
19 |
+
get_yaml_loader,
|
20 |
+
is_dict_annotation,
|
21 |
+
is_list_annotation,
|
22 |
+
is_primitive_dict,
|
23 |
+
is_primitive_type,
|
24 |
+
is_structured_config,
|
25 |
+
)
|
26 |
+
from .base import Container, ContainerMetadata, Node
|
27 |
+
from .errors import MissingMandatoryValue, ReadonlyConfigError, ValidationError
|
28 |
+
|
29 |
+
DEFAULT_VALUE_MARKER: Any = str("__DEFAULT_VALUE_MARKER__")
|
30 |
+
|
31 |
+
|
32 |
+
class BaseContainer(Container, ABC):
|
33 |
+
# static
|
34 |
+
_resolvers: Dict[str, Any] = {}
|
35 |
+
|
36 |
+
def __init__(self, parent: Optional["Container"], metadata: ContainerMetadata):
|
37 |
+
super().__init__(parent=parent, metadata=metadata)
|
38 |
+
self.__dict__["_content"] = None
|
39 |
+
self._normalize_ref_type()
|
40 |
+
|
41 |
+
def _normalize_ref_type(self) -> None:
|
42 |
+
if self._metadata.ref_type is None:
|
43 |
+
self._metadata.ref_type = Any # type: ignore
|
44 |
+
|
45 |
+
def _resolve_with_default(
|
46 |
+
self,
|
47 |
+
key: Union[str, int, Enum],
|
48 |
+
value: Any,
|
49 |
+
default_value: Any = DEFAULT_VALUE_MARKER,
|
50 |
+
) -> Any:
|
51 |
+
"""returns the value with the specified key, like obj.key and obj['key']"""
|
52 |
+
|
53 |
+
def is_mandatory_missing(val: Any) -> bool:
|
54 |
+
return get_value_kind(val) == ValueKind.MANDATORY_MISSING # type: ignore
|
55 |
+
|
56 |
+
value = _get_value(value)
|
57 |
+
has_default = default_value is not DEFAULT_VALUE_MARKER
|
58 |
+
if has_default and (value is None or is_mandatory_missing(value)):
|
59 |
+
return default_value
|
60 |
+
|
61 |
+
resolved = self._resolve_interpolation(
|
62 |
+
key=key,
|
63 |
+
value=value,
|
64 |
+
throw_on_missing=not has_default,
|
65 |
+
throw_on_resolution_failure=not has_default,
|
66 |
+
)
|
67 |
+
if resolved is None and has_default:
|
68 |
+
return default_value
|
69 |
+
|
70 |
+
if is_mandatory_missing(resolved):
|
71 |
+
if has_default:
|
72 |
+
return default_value
|
73 |
+
else:
|
74 |
+
raise MissingMandatoryValue("Missing mandatory value: $FULL_KEY")
|
75 |
+
|
76 |
+
return _get_value(resolved)
|
77 |
+
|
78 |
+
def __str__(self) -> str:
|
79 |
+
return self.__repr__()
|
80 |
+
|
81 |
+
def __repr__(self) -> str:
|
82 |
+
if self.__dict__["_content"] is None:
|
83 |
+
return "None"
|
84 |
+
elif self._is_interpolation() or self._is_missing():
|
85 |
+
v = self.__dict__["_content"]
|
86 |
+
return f"'{v}'"
|
87 |
+
else:
|
88 |
+
return self.__dict__["_content"].__repr__() # type: ignore
|
89 |
+
|
90 |
+
# Support pickle
|
91 |
+
def __getstate__(self) -> Dict[str, Any]:
|
92 |
+
return self.__dict__
|
93 |
+
|
94 |
+
# Support pickle
|
95 |
+
def __setstate__(self, d: Dict[str, Any]) -> None:
|
96 |
+
self.__dict__.update(d)
|
97 |
+
|
98 |
+
@abstractmethod
|
99 |
+
def __delitem__(self, key: Any) -> None:
|
100 |
+
...
|
101 |
+
|
102 |
+
def __len__(self) -> int:
|
103 |
+
return self.__dict__["_content"].__len__() # type: ignore
|
104 |
+
|
105 |
+
def merge_with_cli(self) -> None:
|
106 |
+
args_list = sys.argv[1:]
|
107 |
+
self.merge_with_dotlist(args_list)
|
108 |
+
|
109 |
+
def merge_with_dotlist(self, dotlist: List[str]) -> None:
|
110 |
+
from omegaconf import OmegaConf
|
111 |
+
|
112 |
+
def fail() -> None:
|
113 |
+
raise ValueError("Input list must be a list or a tuple of strings")
|
114 |
+
|
115 |
+
if not isinstance(dotlist, (list, tuple)):
|
116 |
+
fail()
|
117 |
+
|
118 |
+
for arg in dotlist:
|
119 |
+
if not isinstance(arg, str):
|
120 |
+
fail()
|
121 |
+
|
122 |
+
idx = arg.find("=")
|
123 |
+
if idx == -1:
|
124 |
+
key = arg
|
125 |
+
value = None
|
126 |
+
else:
|
127 |
+
key = arg[0:idx]
|
128 |
+
value = arg[idx + 1 :]
|
129 |
+
value = yaml.load(value, Loader=get_yaml_loader())
|
130 |
+
|
131 |
+
OmegaConf.update(self, key, value, merge=True)
|
132 |
+
|
133 |
+
def select(self, key: str, throw_on_missing: bool = False) -> Any:
|
134 |
+
from omegaconf import OmegaConf
|
135 |
+
|
136 |
+
warnings.warn(
|
137 |
+
"select() is deprecated, use OmegaConf.select(). (Since 2.0)",
|
138 |
+
category=UserWarning,
|
139 |
+
stacklevel=2,
|
140 |
+
)
|
141 |
+
|
142 |
+
return OmegaConf.select(self, key, throw_on_missing)
|
143 |
+
|
144 |
+
def update_node(self, key: str, value: Any = None) -> None:
|
145 |
+
from omegaconf import OmegaConf
|
146 |
+
|
147 |
+
warnings.warn(
|
148 |
+
"update_node() is deprecated, use OmegaConf.update(). (Since 2.0)",
|
149 |
+
category=UserWarning,
|
150 |
+
stacklevel=2,
|
151 |
+
)
|
152 |
+
|
153 |
+
OmegaConf.update(self, key, value, merge=False)
|
154 |
+
|
155 |
+
def is_empty(self) -> bool:
|
156 |
+
"""return true if config is empty"""
|
157 |
+
return len(self.__dict__["_content"]) == 0
|
158 |
+
|
159 |
+
@staticmethod
|
160 |
+
def _to_content(
|
161 |
+
conf: Container, resolve: bool, enum_to_str: bool = False
|
162 |
+
) -> Union[None, str, Dict[str, Any], List[Any]]:
|
163 |
+
from .dictconfig import DictConfig
|
164 |
+
from .listconfig import ListConfig
|
165 |
+
|
166 |
+
def convert(val: Node) -> Any:
|
167 |
+
value = val._value()
|
168 |
+
if enum_to_str and isinstance(value, Enum):
|
169 |
+
value = f"{value.name}"
|
170 |
+
|
171 |
+
return value
|
172 |
+
|
173 |
+
assert isinstance(conf, Container)
|
174 |
+
if conf._is_none():
|
175 |
+
return None
|
176 |
+
elif conf._is_interpolation() and not resolve:
|
177 |
+
inter = conf._value()
|
178 |
+
assert isinstance(inter, str)
|
179 |
+
return inter
|
180 |
+
elif conf._is_missing():
|
181 |
+
return "???"
|
182 |
+
elif isinstance(conf, DictConfig):
|
183 |
+
retdict: Dict[str, Any] = {}
|
184 |
+
for key in conf.keys():
|
185 |
+
node = conf._get_node(key)
|
186 |
+
assert node is not None
|
187 |
+
if resolve:
|
188 |
+
node = node._dereference_node(
|
189 |
+
throw_on_missing=False, throw_on_resolution_failure=True
|
190 |
+
)
|
191 |
+
|
192 |
+
assert node is not None
|
193 |
+
if isinstance(node, Container):
|
194 |
+
retdict[key] = BaseContainer._to_content(
|
195 |
+
node, resolve=resolve, enum_to_str=enum_to_str
|
196 |
+
)
|
197 |
+
else:
|
198 |
+
retdict[key] = convert(node)
|
199 |
+
return retdict
|
200 |
+
elif isinstance(conf, ListConfig):
|
201 |
+
retlist: List[Any] = []
|
202 |
+
for index in range(len(conf)):
|
203 |
+
node = conf._get_node(index)
|
204 |
+
assert node is not None
|
205 |
+
if resolve:
|
206 |
+
node = node._dereference_node(
|
207 |
+
throw_on_missing=False, throw_on_resolution_failure=True
|
208 |
+
)
|
209 |
+
assert node is not None
|
210 |
+
if isinstance(node, Container):
|
211 |
+
item = BaseContainer._to_content(
|
212 |
+
node, resolve=resolve, enum_to_str=enum_to_str
|
213 |
+
)
|
214 |
+
retlist.append(item)
|
215 |
+
else:
|
216 |
+
retlist.append(convert(node))
|
217 |
+
|
218 |
+
return retlist
|
219 |
+
|
220 |
+
assert False
|
221 |
+
|
222 |
+
def pretty(self, resolve: bool = False, sort_keys: bool = False) -> str:
|
223 |
+
from omegaconf import OmegaConf
|
224 |
+
|
225 |
+
warnings.warn(
|
226 |
+
dedent(
|
227 |
+
"""\
|
228 |
+
cfg.pretty() is deprecated and will be removed in a future version.
|
229 |
+
Use OmegaConf.to_yaml(cfg)
|
230 |
+
"""
|
231 |
+
),
|
232 |
+
category=UserWarning,
|
233 |
+
)
|
234 |
+
|
235 |
+
return OmegaConf.to_yaml(self, resolve=resolve, sort_keys=sort_keys)
|
236 |
+
|
237 |
+
@staticmethod
|
238 |
+
def _map_merge(dest: "BaseContainer", src: "BaseContainer") -> None:
|
239 |
+
"""merge src into dest and return a new copy, does not modified input"""
|
240 |
+
from omegaconf import DictConfig, OmegaConf, ValueNode
|
241 |
+
|
242 |
+
assert isinstance(dest, DictConfig)
|
243 |
+
assert isinstance(src, DictConfig)
|
244 |
+
src_type = src._metadata.object_type
|
245 |
+
|
246 |
+
# if source DictConfig is an interpolation set the DictConfig one to be the same interpolation.
|
247 |
+
if src._is_interpolation():
|
248 |
+
dest._set_value(src._value())
|
249 |
+
return
|
250 |
+
# if source DictConfig is missing set the DictConfig one to be missing too.
|
251 |
+
if src._is_missing():
|
252 |
+
dest._set_value("???")
|
253 |
+
return
|
254 |
+
dest._validate_set_merge_impl(key=None, value=src, is_assign=False)
|
255 |
+
|
256 |
+
def expand(node: Container) -> None:
|
257 |
+
type_ = get_ref_type(node)
|
258 |
+
if type_ is not None:
|
259 |
+
_is_optional, type_ = _resolve_optional(type_)
|
260 |
+
if is_dict_annotation(type_):
|
261 |
+
node._set_value({})
|
262 |
+
elif is_list_annotation(type_):
|
263 |
+
node._set_value([])
|
264 |
+
else:
|
265 |
+
node._set_value(type_)
|
266 |
+
|
267 |
+
if dest._is_interpolation() or dest._is_missing():
|
268 |
+
expand(dest)
|
269 |
+
|
270 |
+
for key, src_value in src.items_ex(resolve=False):
|
271 |
+
|
272 |
+
dest_node = dest._get_node(key, validate_access=False)
|
273 |
+
if isinstance(dest_node, Container) and OmegaConf.is_none(dest, key):
|
274 |
+
if not OmegaConf.is_none(src_value):
|
275 |
+
expand(dest_node)
|
276 |
+
|
277 |
+
if dest_node is not None:
|
278 |
+
if dest_node._is_interpolation():
|
279 |
+
target_node = dest_node._dereference_node(
|
280 |
+
throw_on_resolution_failure=False
|
281 |
+
)
|
282 |
+
if isinstance(target_node, Container):
|
283 |
+
dest[key] = target_node
|
284 |
+
dest_node = dest._get_node(key)
|
285 |
+
|
286 |
+
if is_structured_config(dest._metadata.element_type):
|
287 |
+
dest[key] = DictConfig(content=dest._metadata.element_type, parent=dest)
|
288 |
+
dest_node = dest._get_node(key)
|
289 |
+
|
290 |
+
if dest_node is not None:
|
291 |
+
if isinstance(dest_node, BaseContainer):
|
292 |
+
if isinstance(src_value, BaseContainer):
|
293 |
+
dest._validate_merge(key=key, value=src_value)
|
294 |
+
dest_node._merge_with(src_value)
|
295 |
+
else:
|
296 |
+
dest.__setitem__(key, src_value)
|
297 |
+
else:
|
298 |
+
if isinstance(src_value, BaseContainer):
|
299 |
+
dest.__setitem__(key, src_value)
|
300 |
+
else:
|
301 |
+
assert isinstance(dest_node, ValueNode)
|
302 |
+
try:
|
303 |
+
dest_node._set_value(src_value)
|
304 |
+
except (ValidationError, ReadonlyConfigError) as e:
|
305 |
+
dest._format_and_raise(key=key, value=src_value, cause=e)
|
306 |
+
else:
|
307 |
+
from omegaconf import open_dict
|
308 |
+
|
309 |
+
if is_structured_config(src_type):
|
310 |
+
# verified to be compatible above in _validate_set_merge_impl
|
311 |
+
with open_dict(dest):
|
312 |
+
dest[key] = src._get_node(key)
|
313 |
+
else:
|
314 |
+
dest[key] = src._get_node(key)
|
315 |
+
|
316 |
+
if src_type is not None and not is_primitive_dict(src_type):
|
317 |
+
dest._metadata.object_type = src_type
|
318 |
+
|
319 |
+
# explicit flags on the source config are replacing the flag values in the destination
|
320 |
+
for flag, value in src._metadata.flags.items():
|
321 |
+
if value is not None:
|
322 |
+
dest._set_flag(flag, value)
|
323 |
+
|
324 |
+
def merge_with(
|
325 |
+
self,
|
326 |
+
*others: Union["BaseContainer", Dict[str, Any], List[Any], Tuple[Any], Any],
|
327 |
+
) -> None:
|
328 |
+
try:
|
329 |
+
self._merge_with(*others)
|
330 |
+
except Exception as e:
|
331 |
+
self._format_and_raise(key=None, value=None, cause=e)
|
332 |
+
|
333 |
+
def _merge_with(
|
334 |
+
self,
|
335 |
+
*others: Union["BaseContainer", Dict[str, Any], List[Any], Tuple[Any], Any],
|
336 |
+
) -> None:
|
337 |
+
from .dictconfig import DictConfig
|
338 |
+
from .listconfig import ListConfig
|
339 |
+
from .omegaconf import OmegaConf
|
340 |
+
|
341 |
+
"""merge a list of other Config objects into this one, overriding as needed"""
|
342 |
+
for other in others:
|
343 |
+
if other is None:
|
344 |
+
raise ValueError("Cannot merge with a None config")
|
345 |
+
other = _ensure_container(other)
|
346 |
+
if isinstance(self, DictConfig) and isinstance(other, DictConfig):
|
347 |
+
BaseContainer._map_merge(self, other)
|
348 |
+
elif isinstance(self, ListConfig) and isinstance(other, ListConfig):
|
349 |
+
self.__dict__["_content"] = []
|
350 |
+
|
351 |
+
if other._is_interpolation():
|
352 |
+
self._set_value(other._value())
|
353 |
+
elif other._is_missing():
|
354 |
+
self._set_value("???")
|
355 |
+
elif other._is_none():
|
356 |
+
self._set_value(None)
|
357 |
+
else:
|
358 |
+
et = self._metadata.element_type
|
359 |
+
if is_structured_config(et):
|
360 |
+
prototype = OmegaConf.structured(et)
|
361 |
+
for item in other:
|
362 |
+
if isinstance(item, DictConfig):
|
363 |
+
item = OmegaConf.merge(prototype, item)
|
364 |
+
self.append(item)
|
365 |
+
|
366 |
+
else:
|
367 |
+
for item in other:
|
368 |
+
self.append(item)
|
369 |
+
|
370 |
+
# explicit flags on the source config are replacing the flag values in the destination
|
371 |
+
for flag, value in other._metadata.flags.items():
|
372 |
+
if value is not None:
|
373 |
+
self._set_flag(flag, value)
|
374 |
+
else:
|
375 |
+
raise TypeError("Cannot merge DictConfig with ListConfig")
|
376 |
+
|
377 |
+
# recursively correct the parent hierarchy after the merge
|
378 |
+
self._re_parent()
|
379 |
+
|
380 |
+
# noinspection PyProtectedMember
|
381 |
+
def _set_item_impl(self, key: Any, value: Any) -> None:
|
382 |
+
"""
|
383 |
+
Changes the value of the node key with the desired value. If the node key doesn't
|
384 |
+
exist it creates a new one.
|
385 |
+
"""
|
386 |
+
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
|
387 |
+
|
388 |
+
from .nodes import AnyNode, ValueNode
|
389 |
+
|
390 |
+
if isinstance(value, Node):
|
391 |
+
try:
|
392 |
+
old = value._key()
|
393 |
+
value._set_key(key)
|
394 |
+
self._validate_set(key, value)
|
395 |
+
finally:
|
396 |
+
value._set_key(old)
|
397 |
+
else:
|
398 |
+
self._validate_set(key, value)
|
399 |
+
|
400 |
+
if self._get_flag("readonly"):
|
401 |
+
raise ReadonlyConfigError("Cannot change read-only config container")
|
402 |
+
|
403 |
+
input_config = isinstance(value, Container)
|
404 |
+
target_node_ref = self._get_node(key)
|
405 |
+
special_value = value is None or value == "???"
|
406 |
+
|
407 |
+
input_node = isinstance(value, ValueNode)
|
408 |
+
if isinstance(self.__dict__["_content"], dict):
|
409 |
+
target_node = key in self.__dict__["_content"] and isinstance(
|
410 |
+
target_node_ref, ValueNode
|
411 |
+
)
|
412 |
+
|
413 |
+
elif isinstance(self.__dict__["_content"], list):
|
414 |
+
target_node = isinstance(target_node_ref, ValueNode)
|
415 |
+
# We use set_value if:
|
416 |
+
# 1. Target node is a container and the value is MISSING or None
|
417 |
+
# 2. Target node is a container and has an explicit ref_type
|
418 |
+
# 3. If the target is a NodeValue then it should set his value.
|
419 |
+
# Furthermore if it's an AnyNode it should wrap when the input is
|
420 |
+
# a container and set when the input is an compatible type(primitive type).
|
421 |
+
|
422 |
+
should_set_value = target_node_ref is not None and (
|
423 |
+
(
|
424 |
+
isinstance(target_node_ref, Container)
|
425 |
+
and (special_value or target_node_ref._has_ref_type())
|
426 |
+
)
|
427 |
+
or (target_node and not isinstance(target_node_ref, AnyNode))
|
428 |
+
or (isinstance(target_node_ref, AnyNode) and is_primitive_type(value))
|
429 |
+
)
|
430 |
+
|
431 |
+
def wrap(key: Any, val: Any) -> Node:
|
432 |
+
is_optional = True
|
433 |
+
if not is_structured_config(val):
|
434 |
+
ref_type = self._metadata.element_type
|
435 |
+
else:
|
436 |
+
target = self._get_node(key)
|
437 |
+
if target is None:
|
438 |
+
if is_structured_config(val):
|
439 |
+
ref_type = OmegaConf.get_type(val)
|
440 |
+
else:
|
441 |
+
is_optional = target._is_optional()
|
442 |
+
ref_type = target._metadata.ref_type
|
443 |
+
return _maybe_wrap(
|
444 |
+
ref_type=ref_type,
|
445 |
+
key=key,
|
446 |
+
value=val,
|
447 |
+
is_optional=is_optional,
|
448 |
+
parent=self,
|
449 |
+
)
|
450 |
+
|
451 |
+
def assign(value_key: Any, value_to_assign: Any) -> None:
|
452 |
+
v = copy.deepcopy(value_to_assign)
|
453 |
+
v._set_parent(self)
|
454 |
+
v._set_key(value_key)
|
455 |
+
self.__dict__["_content"][value_key] = v
|
456 |
+
|
457 |
+
if input_node and target_node:
|
458 |
+
# both nodes, replace existing node with new one
|
459 |
+
assign(key, value)
|
460 |
+
elif not input_node and target_node:
|
461 |
+
# input is not node, can be primitive or config
|
462 |
+
if should_set_value:
|
463 |
+
self.__dict__["_content"][key]._set_value(value)
|
464 |
+
elif input_config:
|
465 |
+
assign(key, value)
|
466 |
+
else:
|
467 |
+
self.__dict__["_content"][key] = wrap(key, value)
|
468 |
+
elif input_node and not target_node:
|
469 |
+
# target must be config, replace target with input node
|
470 |
+
assign(key, value)
|
471 |
+
elif not input_node and not target_node:
|
472 |
+
if should_set_value:
|
473 |
+
self.__dict__["_content"][key]._set_value(value)
|
474 |
+
elif input_config:
|
475 |
+
assign(key, value)
|
476 |
+
else:
|
477 |
+
self.__dict__["_content"][key] = wrap(key, value)
|
478 |
+
|
479 |
+
@staticmethod
|
480 |
+
def _item_eq(
|
481 |
+
c1: Container, k1: Union[str, int], c2: Container, k2: Union[str, int]
|
482 |
+
) -> bool:
|
483 |
+
v1 = c1._get_node(k1)
|
484 |
+
v2 = c2._get_node(k2)
|
485 |
+
assert v1 is not None and v2 is not None
|
486 |
+
|
487 |
+
if v1._is_none() and v2._is_none():
|
488 |
+
return True
|
489 |
+
|
490 |
+
if v1._is_missing() and v2._is_missing():
|
491 |
+
return True
|
492 |
+
|
493 |
+
v1_inter = v1._is_interpolation()
|
494 |
+
v2_inter = v2._is_interpolation()
|
495 |
+
dv1: Optional[Node] = v1
|
496 |
+
dv2: Optional[Node] = v2
|
497 |
+
|
498 |
+
if v1_inter:
|
499 |
+
dv1 = v1._dereference_node(
|
500 |
+
throw_on_missing=False, throw_on_resolution_failure=False
|
501 |
+
)
|
502 |
+
if v2_inter:
|
503 |
+
dv2 = v2._dereference_node(
|
504 |
+
throw_on_missing=False, throw_on_resolution_failure=False
|
505 |
+
)
|
506 |
+
|
507 |
+
if v1_inter and v2_inter:
|
508 |
+
if dv1 is None or dv2 is None:
|
509 |
+
return v1 == v2
|
510 |
+
else:
|
511 |
+
# both are not none, if both are containers compare as container
|
512 |
+
if isinstance(dv1, Container) and isinstance(dv2, Container):
|
513 |
+
if dv1 != dv2:
|
514 |
+
return False
|
515 |
+
dv1 = _get_value(dv1)
|
516 |
+
dv2 = _get_value(dv2)
|
517 |
+
return dv1 == dv2
|
518 |
+
elif not v1_inter and not v2_inter:
|
519 |
+
v1 = _get_value(v1)
|
520 |
+
v2 = _get_value(v2)
|
521 |
+
return v1 == v2
|
522 |
+
else:
|
523 |
+
dv1 = _get_value(dv1)
|
524 |
+
dv2 = _get_value(dv2)
|
525 |
+
return dv1 == dv2
|
526 |
+
|
527 |
+
def _is_none(self) -> bool:
|
528 |
+
return self.__dict__["_content"] is None
|
529 |
+
|
530 |
+
def _is_missing(self) -> bool:
|
531 |
+
try:
|
532 |
+
self._dereference_node(
|
533 |
+
throw_on_resolution_failure=False, throw_on_missing=True
|
534 |
+
)
|
535 |
+
return False
|
536 |
+
except MissingMandatoryValue:
|
537 |
+
ret = True
|
538 |
+
|
539 |
+
assert isinstance(ret, bool)
|
540 |
+
return ret
|
541 |
+
|
542 |
+
def _is_optional(self) -> bool:
|
543 |
+
return self.__dict__["_metadata"].optional is True
|
544 |
+
|
545 |
+
def _is_interpolation(self) -> bool:
|
546 |
+
return _is_interpolation(self.__dict__["_content"])
|
547 |
+
|
548 |
+
@abstractmethod
|
549 |
+
def _validate_get(self, key: Any, value: Any = None) -> None:
|
550 |
+
...
|
551 |
+
|
552 |
+
@abstractmethod
|
553 |
+
def _validate_set(self, key: Any, value: Any) -> None:
|
554 |
+
...
|
555 |
+
|
556 |
+
def _value(self) -> Any:
|
557 |
+
return self.__dict__["_content"]
|
558 |
+
|
559 |
+
def _get_full_key(self, key: Union[str, Enum, int, slice, None]) -> str:
|
560 |
+
from .listconfig import ListConfig
|
561 |
+
from .omegaconf import _select_one
|
562 |
+
|
563 |
+
if not isinstance(key, (int, str, Enum, slice, type(None))):
|
564 |
+
return ""
|
565 |
+
|
566 |
+
def _slice_to_str(x: slice) -> str:
|
567 |
+
if x.step is not None:
|
568 |
+
return f"{x.start}:{x.stop}:{x.step}"
|
569 |
+
else:
|
570 |
+
return f"{x.start}:{x.stop}"
|
571 |
+
|
572 |
+
def prepand(full_key: str, parent_type: Any, cur_type: Any, key: Any) -> str:
|
573 |
+
if isinstance(key, slice):
|
574 |
+
key = _slice_to_str(key)
|
575 |
+
elif isinstance(key, Enum):
|
576 |
+
key = key.name
|
577 |
+
|
578 |
+
if issubclass(parent_type, ListConfig):
|
579 |
+
if full_key != "":
|
580 |
+
if issubclass(cur_type, ListConfig):
|
581 |
+
full_key = f"[{key}]{full_key}"
|
582 |
+
else:
|
583 |
+
full_key = f"[{key}].{full_key}"
|
584 |
+
else:
|
585 |
+
full_key = f"[{key}]"
|
586 |
+
else:
|
587 |
+
if full_key == "":
|
588 |
+
full_key = key
|
589 |
+
else:
|
590 |
+
if issubclass(cur_type, ListConfig):
|
591 |
+
full_key = f"{key}{full_key}"
|
592 |
+
else:
|
593 |
+
full_key = f"{key}.{full_key}"
|
594 |
+
return full_key
|
595 |
+
|
596 |
+
if key is not None and key != "":
|
597 |
+
assert isinstance(self, Container)
|
598 |
+
cur, _ = _select_one(
|
599 |
+
c=self, key=str(key), throw_on_missing=False, throw_on_type_error=False
|
600 |
+
)
|
601 |
+
if cur is None:
|
602 |
+
cur = self
|
603 |
+
full_key = prepand("", type(cur), None, key)
|
604 |
+
if cur._key() is not None:
|
605 |
+
full_key = prepand(
|
606 |
+
full_key, type(cur._get_parent()), type(cur), cur._key()
|
607 |
+
)
|
608 |
+
else:
|
609 |
+
full_key = prepand("", type(cur._get_parent()), type(cur), cur._key())
|
610 |
+
else:
|
611 |
+
cur = self
|
612 |
+
if cur._key() is None:
|
613 |
+
return ""
|
614 |
+
full_key = self._key()
|
615 |
+
|
616 |
+
assert cur is not None
|
617 |
+
while cur._get_parent() is not None:
|
618 |
+
cur = cur._get_parent()
|
619 |
+
assert cur is not None
|
620 |
+
key = cur._key()
|
621 |
+
if key is not None:
|
622 |
+
full_key = prepand(
|
623 |
+
full_key, type(cur._get_parent()), type(cur), cur._key()
|
624 |
+
)
|
625 |
+
|
626 |
+
return full_key
|
omegaconf/dictconfig.py
ADDED
@@ -0,0 +1,579 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ing import (
|
4 |
+
AbstractSet,
|
5 |
+
Any,
|
6 |
+
Dict,
|
7 |
+
Iterable,
|
8 |
+
Iterator,
|
9 |
+
List,
|
10 |
+
MutableMapping,
|
11 |
+
Optional,
|
12 |
+
Tuple,
|
13 |
+
Type,
|
14 |
+
Union,
|
15 |
+
)
|
16 |
+
|
17 |
+
from ._utils import (
|
18 |
+
ValueKind,
|
19 |
+
_is_interpolation,
|
20 |
+
get_structured_config_data,
|
21 |
+
get_type_of,
|
22 |
+
get_value_kind,
|
23 |
+
is_dict,
|
24 |
+
is_generic_dict,
|
25 |
+
is_generic_list,
|
26 |
+
is_primitive_dict,
|
27 |
+
is_structured_config,
|
28 |
+
is_structured_config_frozen,
|
29 |
+
type_str,
|
30 |
+
)
|
31 |
+
from .base import Container, ContainerMetadata, Node
|
32 |
+
from .basecontainer import DEFAULT_VALUE_MARKER, BaseContainer
|
33 |
+
from .errors import (
|
34 |
+
ConfigAttributeError,
|
35 |
+
ConfigKeyError,
|
36 |
+
ConfigTypeError,
|
37 |
+
KeyValidationError,
|
38 |
+
MissingMandatoryValue,
|
39 |
+
OmegaConfBaseException,
|
40 |
+
ReadonlyConfigError,
|
41 |
+
UnsupportedInterpolationType,
|
42 |
+
ValidationError,
|
43 |
+
)
|
44 |
+
from .nodes import EnumNode, ValueNode
|
45 |
+
|
46 |
+
|
47 |
+
class DictConfig(BaseContainer, MutableMapping[str, Any]):
|
48 |
+
|
49 |
+
_metadata: ContainerMetadata
|
50 |
+
|
51 |
+
def __init__(
|
52 |
+
self,
|
53 |
+
content: Union[Dict[str, Any], Any],
|
54 |
+
key: Any = None,
|
55 |
+
parent: Optional[Container] = None,
|
56 |
+
ref_type: Union[Type[Any], Any] = Any,
|
57 |
+
key_type: Optional[Type[Any]] = None,
|
58 |
+
element_type: Optional[Type[Any]] = None,
|
59 |
+
is_optional: bool = True,
|
60 |
+
) -> None:
|
61 |
+
super().__init__(
|
62 |
+
parent=parent,
|
63 |
+
metadata=ContainerMetadata(
|
64 |
+
key=key,
|
65 |
+
optional=is_optional,
|
66 |
+
ref_type=ref_type,
|
67 |
+
object_type=None,
|
68 |
+
key_type=key_type,
|
69 |
+
element_type=element_type,
|
70 |
+
),
|
71 |
+
)
|
72 |
+
|
73 |
+
if is_structured_config(content) or is_structured_config(ref_type):
|
74 |
+
self._set_value(content)
|
75 |
+
if is_structured_config_frozen(content) or is_structured_config_frozen(
|
76 |
+
ref_type
|
77 |
+
):
|
78 |
+
self._set_flag("readonly", True)
|
79 |
+
|
80 |
+
else:
|
81 |
+
self._set_value(content)
|
82 |
+
if isinstance(content, DictConfig):
|
83 |
+
metadata = copy.deepcopy(content._metadata)
|
84 |
+
metadata.key = key
|
85 |
+
metadata.optional = is_optional
|
86 |
+
metadata.element_type = element_type
|
87 |
+
metadata.key_type = key_type
|
88 |
+
self.__dict__["_metadata"] = metadata
|
89 |
+
|
90 |
+
def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "DictConfig":
|
91 |
+
res = DictConfig({})
|
92 |
+
for k, v in self.__dict__.items():
|
93 |
+
res.__dict__[k] = copy.deepcopy(v, memo=memo)
|
94 |
+
res._re_parent()
|
95 |
+
return res
|
96 |
+
|
97 |
+
def __copy__(self) -> "DictConfig":
|
98 |
+
from .omegaconf import MISSING
|
99 |
+
|
100 |
+
res = DictConfig(content=None)
|
101 |
+
for k, v in self.__dict__.items():
|
102 |
+
res.__dict__[k] = copy.copy(v)
|
103 |
+
res._re_parent()
|
104 |
+
content = self.__dict__["_content"]
|
105 |
+
if content != MISSING and content is not None:
|
106 |
+
for k, v in content.items():
|
107 |
+
if isinstance(v, ValueNode):
|
108 |
+
res.__dict__["_content"][k] = copy.copy(v)
|
109 |
+
|
110 |
+
return res
|
111 |
+
|
112 |
+
def copy(self) -> "DictConfig":
|
113 |
+
return copy.copy(self)
|
114 |
+
|
115 |
+
def _is_typed(self) -> bool:
|
116 |
+
return self._metadata.object_type not in (Any, None) and not is_dict(
|
117 |
+
self._metadata.object_type
|
118 |
+
)
|
119 |
+
|
120 |
+
def _validate_get(self, key: Any, value: Any = None) -> None:
|
121 |
+
is_typed = self._is_typed()
|
122 |
+
|
123 |
+
is_struct = self._get_flag("struct") is True
|
124 |
+
if key not in self.__dict__["_content"]:
|
125 |
+
if is_typed:
|
126 |
+
# do not raise an exception if struct is explicitly set to False
|
127 |
+
if self._get_node_flag("struct") is False:
|
128 |
+
return
|
129 |
+
if is_typed or is_struct:
|
130 |
+
if is_typed:
|
131 |
+
assert self._metadata.object_type is not None
|
132 |
+
msg = f"Key '{key}' not in '{self._metadata.object_type.__name__}'"
|
133 |
+
else:
|
134 |
+
msg = f"Key '{key}' is not in struct"
|
135 |
+
self._format_and_raise(
|
136 |
+
key=key, value=value, cause=ConfigAttributeError(msg)
|
137 |
+
)
|
138 |
+
|
139 |
+
def _validate_merge(self, key: Any, value: Any) -> None:
|
140 |
+
self._validate_set_merge_impl(key, value, is_assign=False)
|
141 |
+
|
142 |
+
def _validate_set(self, key: Any, value: Any) -> None:
|
143 |
+
self._validate_set_merge_impl(key, value, is_assign=True)
|
144 |
+
|
145 |
+
def _validate_set_merge_impl(self, key: Any, value: Any, is_assign: bool) -> None:
|
146 |
+
from omegaconf import OmegaConf
|
147 |
+
|
148 |
+
vk = get_value_kind(value)
|
149 |
+
if vk in (ValueKind.INTERPOLATION, ValueKind.STR_INTERPOLATION):
|
150 |
+
return
|
151 |
+
|
152 |
+
if OmegaConf.is_none(value):
|
153 |
+
if key is not None:
|
154 |
+
child = self._get_node(key)
|
155 |
+
if child is not None and not child._is_optional():
|
156 |
+
self._format_and_raise(
|
157 |
+
key=key,
|
158 |
+
value=value,
|
159 |
+
cause=ValidationError("child '$FULL_KEY' is not Optional"),
|
160 |
+
)
|
161 |
+
else:
|
162 |
+
if not self._is_optional():
|
163 |
+
self._format_and_raise(
|
164 |
+
key=None,
|
165 |
+
value=value,
|
166 |
+
cause=ValidationError("field '$FULL_KEY' is not Optional"),
|
167 |
+
)
|
168 |
+
|
169 |
+
if value == "???":
|
170 |
+
return
|
171 |
+
|
172 |
+
target: Optional[Node]
|
173 |
+
if key is None:
|
174 |
+
target = self
|
175 |
+
else:
|
176 |
+
target = self._get_node(key)
|
177 |
+
|
178 |
+
if target is None:
|
179 |
+
return
|
180 |
+
|
181 |
+
def is_typed(c: Any) -> bool:
|
182 |
+
return isinstance(c, DictConfig) and c._metadata.ref_type not in (Any, dict)
|
183 |
+
|
184 |
+
if not is_typed(target):
|
185 |
+
return
|
186 |
+
|
187 |
+
# target must be optional by now. no need to check the type of value if None.
|
188 |
+
if value is None:
|
189 |
+
return
|
190 |
+
|
191 |
+
target_type = target._metadata.ref_type
|
192 |
+
value_type = OmegaConf.get_type(value)
|
193 |
+
|
194 |
+
if is_dict(value_type) and is_dict(target_type):
|
195 |
+
return
|
196 |
+
|
197 |
+
if is_generic_list(target_type) or is_generic_dict(target_type):
|
198 |
+
return
|
199 |
+
# TODO: simplify this flow. (if assign validate assign else validate merge)
|
200 |
+
# is assignment illegal?
|
201 |
+
validation_error = (
|
202 |
+
target_type is not None
|
203 |
+
and value_type is not None
|
204 |
+
and not issubclass(value_type, target_type)
|
205 |
+
)
|
206 |
+
|
207 |
+
if not is_assign:
|
208 |
+
# merge
|
209 |
+
# Merging of a dictionary is allowed even if assignment is illegal (merge would do deeper checks)
|
210 |
+
validation_error = not is_dict(value_type) and validation_error
|
211 |
+
|
212 |
+
if validation_error:
|
213 |
+
assert value_type is not None
|
214 |
+
assert target_type is not None
|
215 |
+
msg = (
|
216 |
+
f"Invalid type assigned : {type_str(value_type)} is not a "
|
217 |
+
f"subclass of {type_str(target_type)}. value: {value}"
|
218 |
+
)
|
219 |
+
raise ValidationError(msg)
|
220 |
+
|
221 |
+
def _validate_and_normalize_key(self, key: Any) -> Union[str, Enum]:
|
222 |
+
return self._s_validate_and_normalize_key(self._metadata.key_type, key)
|
223 |
+
|
224 |
+
def _s_validate_and_normalize_key(
|
225 |
+
self, key_type: Any, key: Any
|
226 |
+
) -> Union[str, Enum]:
|
227 |
+
if key_type is None:
|
228 |
+
for t in (str, Enum):
|
229 |
+
try:
|
230 |
+
return self._s_validate_and_normalize_key(key_type=t, key=key)
|
231 |
+
except KeyValidationError:
|
232 |
+
pass
|
233 |
+
raise KeyValidationError("Incompatible key type '$KEY_TYPE'")
|
234 |
+
elif key_type == str:
|
235 |
+
if not isinstance(key, str):
|
236 |
+
raise KeyValidationError(
|
237 |
+
f"Key $KEY ($KEY_TYPE) is incompatible with ({key_type.__name__})"
|
238 |
+
)
|
239 |
+
|
240 |
+
return key
|
241 |
+
elif issubclass(key_type, Enum):
|
242 |
+
try:
|
243 |
+
ret = EnumNode.validate_and_convert_to_enum(key_type, key)
|
244 |
+
assert ret is not None
|
245 |
+
return ret
|
246 |
+
except ValidationError:
|
247 |
+
valid = ", ".join([x for x in key_type.__members__.keys()])
|
248 |
+
raise KeyValidationError(
|
249 |
+
f"Key '$KEY' is incompatible with the enum type '{key_type.__name__}', valid: [{valid}]"
|
250 |
+
)
|
251 |
+
else:
|
252 |
+
assert False
|
253 |
+
|
254 |
+
def __setitem__(self, key: Union[str, Enum], value: Any) -> None:
|
255 |
+
try:
|
256 |
+
self.__set_impl(key=key, value=value)
|
257 |
+
except AttributeError as e:
|
258 |
+
self._format_and_raise(
|
259 |
+
key=key, value=value, type_override=ConfigKeyError, cause=e
|
260 |
+
)
|
261 |
+
except Exception as e:
|
262 |
+
self._format_and_raise(key=key, value=value, cause=e)
|
263 |
+
|
264 |
+
def __set_impl(self, key: Union[str, Enum], value: Any) -> None:
|
265 |
+
key = self._validate_and_normalize_key(key)
|
266 |
+
self._set_item_impl(key, value)
|
267 |
+
|
268 |
+
# hide content while inspecting in debugger
|
269 |
+
def __dir__(self) -> Iterable[str]:
|
270 |
+
if self._is_missing() or self._is_none():
|
271 |
+
return []
|
272 |
+
return self.__dict__["_content"].keys() # type: ignore
|
273 |
+
|
274 |
+
def __setattr__(self, key: str, value: Any) -> None:
|
275 |
+
"""
|
276 |
+
Allow assigning attributes to DictConfig
|
277 |
+
:param key:
|
278 |
+
:param value:
|
279 |
+
:return:
|
280 |
+
"""
|
281 |
+
try:
|
282 |
+
self.__set_impl(key, value)
|
283 |
+
except Exception as e:
|
284 |
+
if isinstance(e, OmegaConfBaseException) and e._initialized:
|
285 |
+
raise e
|
286 |
+
self._format_and_raise(key=key, value=value, cause=e)
|
287 |
+
assert False
|
288 |
+
|
289 |
+
def __getattr__(self, key: str) -> Any:
|
290 |
+
"""
|
291 |
+
Allow accessing dictionary values as attributes
|
292 |
+
:param key:
|
293 |
+
:return:
|
294 |
+
"""
|
295 |
+
try:
|
296 |
+
# PyCharm is sometimes inspecting __members__, be sure to tell it we don't have that.
|
297 |
+
if key == "__members__":
|
298 |
+
raise ConfigAttributeError()
|
299 |
+
|
300 |
+
if key == "__name__":
|
301 |
+
raise ConfigAttributeError()
|
302 |
+
|
303 |
+
return self._get_impl(key=key, default_value=DEFAULT_VALUE_MARKER)
|
304 |
+
except Exception as e:
|
305 |
+
self._format_and_raise(key=key, value=None, cause=e)
|
306 |
+
|
307 |
+
def __getitem__(self, key: Union[str, Enum]) -> Any:
|
308 |
+
"""
|
309 |
+
Allow map style access
|
310 |
+
:param key:
|
311 |
+
:return:
|
312 |
+
"""
|
313 |
+
|
314 |
+
try:
|
315 |
+
return self._get_impl(key=key, default_value=DEFAULT_VALUE_MARKER)
|
316 |
+
except AttributeError as e:
|
317 |
+
self._format_and_raise(
|
318 |
+
key=key, value=None, cause=e, type_override=ConfigKeyError
|
319 |
+
)
|
320 |
+
except Exception as e:
|
321 |
+
self._format_and_raise(key=key, value=None, cause=e)
|
322 |
+
|
323 |
+
def __delitem__(self, key: Union[str, int, Enum]) -> None:
|
324 |
+
if self._get_flag("readonly"):
|
325 |
+
self._format_and_raise(
|
326 |
+
key=key,
|
327 |
+
value=None,
|
328 |
+
cause=ReadonlyConfigError(
|
329 |
+
"DictConfig in read-only mode does not support deletion"
|
330 |
+
),
|
331 |
+
)
|
332 |
+
if self._get_flag("struct"):
|
333 |
+
self._format_and_raise(
|
334 |
+
key=key,
|
335 |
+
value=None,
|
336 |
+
cause=ConfigTypeError(
|
337 |
+
"DictConfig in struct mode does not support deletion"
|
338 |
+
),
|
339 |
+
)
|
340 |
+
if self._is_typed() and self._get_node_flag("struct") is not False:
|
341 |
+
self._format_and_raise(
|
342 |
+
key=key,
|
343 |
+
value=None,
|
344 |
+
cause=ConfigTypeError(
|
345 |
+
f"{type_str(self._metadata.object_type)} (DictConfig) does not support deletion"
|
346 |
+
),
|
347 |
+
)
|
348 |
+
|
349 |
+
del self.__dict__["_content"][key]
|
350 |
+
|
351 |
+
def get(
|
352 |
+
self, key: Union[str, Enum], default_value: Any = DEFAULT_VALUE_MARKER
|
353 |
+
) -> Any:
|
354 |
+
try:
|
355 |
+
return self._get_impl(key=key, default_value=default_value)
|
356 |
+
except Exception as e:
|
357 |
+
self._format_and_raise(key=key, value=None, cause=e)
|
358 |
+
|
359 |
+
def _get_impl(self, key: Union[str, Enum], default_value: Any) -> Any:
|
360 |
+
try:
|
361 |
+
node = self._get_node(key=key)
|
362 |
+
except ConfigAttributeError:
|
363 |
+
if default_value != DEFAULT_VALUE_MARKER:
|
364 |
+
node = default_value
|
365 |
+
else:
|
366 |
+
raise
|
367 |
+
return self._resolve_with_default(
|
368 |
+
key=key, value=node, default_value=default_value
|
369 |
+
)
|
370 |
+
|
371 |
+
def _get_node(
|
372 |
+
self, key: Union[str, Enum], validate_access: bool = True
|
373 |
+
) -> Optional[Node]:
|
374 |
+
try:
|
375 |
+
key = self._validate_and_normalize_key(key)
|
376 |
+
except KeyValidationError:
|
377 |
+
if validate_access:
|
378 |
+
raise
|
379 |
+
else:
|
380 |
+
return None
|
381 |
+
|
382 |
+
if validate_access:
|
383 |
+
self._validate_get(key)
|
384 |
+
|
385 |
+
value: Node = self.__dict__["_content"].get(key)
|
386 |
+
|
387 |
+
return value
|
388 |
+
|
389 |
+
def pop(self, key: Union[str, Enum], default: Any = DEFAULT_VALUE_MARKER) -> Any:
|
390 |
+
try:
|
391 |
+
if self._get_flag("readonly"):
|
392 |
+
raise ReadonlyConfigError("Cannot pop from read-only node")
|
393 |
+
if self._get_flag("struct"):
|
394 |
+
raise ConfigTypeError("DictConfig in struct mode does not support pop")
|
395 |
+
if self._is_typed() and self._get_node_flag("struct") is not False:
|
396 |
+
raise ConfigTypeError(
|
397 |
+
f"{type_str(self._metadata.object_type)} (DictConfig) does not support pop"
|
398 |
+
)
|
399 |
+
key = self._validate_and_normalize_key(key)
|
400 |
+
node = self._get_node(key=key, validate_access=False)
|
401 |
+
if node is not None:
|
402 |
+
value = self._resolve_with_default(
|
403 |
+
key=key, value=node, default_value=default
|
404 |
+
)
|
405 |
+
|
406 |
+
del self[key]
|
407 |
+
return value
|
408 |
+
else:
|
409 |
+
if default is not DEFAULT_VALUE_MARKER:
|
410 |
+
return default
|
411 |
+
else:
|
412 |
+
full = self._get_full_key(key=key)
|
413 |
+
if full != key:
|
414 |
+
raise ConfigKeyError(f"Key not found: '{key}' (path: '{full}')")
|
415 |
+
else:
|
416 |
+
raise ConfigKeyError(f"Key not found: '{key}'")
|
417 |
+
except Exception as e:
|
418 |
+
self._format_and_raise(key=key, value=None, cause=e)
|
419 |
+
|
420 |
+
def keys(self) -> Any:
|
421 |
+
if self._is_missing() or self._is_interpolation() or self._is_none():
|
422 |
+
return list()
|
423 |
+
return self.__dict__["_content"].keys()
|
424 |
+
|
425 |
+
def __contains__(self, key: object) -> bool:
|
426 |
+
"""
|
427 |
+
A key is contained in a DictConfig if there is an associated value and
|
428 |
+
it is not a mandatory missing value ('???').
|
429 |
+
:param key:
|
430 |
+
:return:
|
431 |
+
"""
|
432 |
+
|
433 |
+
key = self._validate_and_normalize_key(key)
|
434 |
+
try:
|
435 |
+
node: Optional[Node] = self._get_node(key)
|
436 |
+
except (KeyError, AttributeError):
|
437 |
+
node = None
|
438 |
+
|
439 |
+
if node is None:
|
440 |
+
return False
|
441 |
+
else:
|
442 |
+
try:
|
443 |
+
self._resolve_with_default(key=key, value=node)
|
444 |
+
return True
|
445 |
+
except UnsupportedInterpolationType:
|
446 |
+
# Value that has unsupported interpolation counts as existing.
|
447 |
+
return True
|
448 |
+
except (MissingMandatoryValue, KeyError):
|
449 |
+
return False
|
450 |
+
|
451 |
+
def __iter__(self) -> Iterator[str]:
|
452 |
+
return iter(self.keys())
|
453 |
+
|
454 |
+
def items(self) -> AbstractSet[Tuple[str, Any]]:
|
455 |
+
return self.items_ex(resolve=True, keys=None)
|
456 |
+
|
457 |
+
def setdefault(self, key: Union[str, Enum], default: Any = None) -> Any:
|
458 |
+
if key in self:
|
459 |
+
ret = self.__getitem__(key)
|
460 |
+
else:
|
461 |
+
ret = default
|
462 |
+
self.__setitem__(key, default)
|
463 |
+
return ret
|
464 |
+
|
465 |
+
def items_ex(
|
466 |
+
self, resolve: bool = True, keys: Optional[List[str]] = None
|
467 |
+
) -> AbstractSet[Tuple[str, Any]]:
|
468 |
+
# Using a dictionary because the keys are ordered
|
469 |
+
items: Dict[Tuple[str, Any], None] = {}
|
470 |
+
for key in self.keys():
|
471 |
+
if resolve:
|
472 |
+
value = self.get(key)
|
473 |
+
else:
|
474 |
+
value = self.__dict__["_content"][key]
|
475 |
+
if isinstance(value, ValueNode):
|
476 |
+
value = value._value()
|
477 |
+
if keys is None or key in keys:
|
478 |
+
items[(key, value)] = None
|
479 |
+
|
480 |
+
return items.keys()
|
481 |
+
|
482 |
+
def __eq__(self, other: Any) -> bool:
|
483 |
+
if other is None:
|
484 |
+
return self.__dict__["_content"] is None
|
485 |
+
if is_primitive_dict(other) or is_structured_config(other):
|
486 |
+
other = DictConfig(other)
|
487 |
+
return DictConfig._dict_conf_eq(self, other)
|
488 |
+
if isinstance(other, DictConfig):
|
489 |
+
return DictConfig._dict_conf_eq(self, other)
|
490 |
+
return NotImplemented
|
491 |
+
|
492 |
+
def __ne__(self, other: Any) -> bool:
|
493 |
+
x = self.__eq__(other)
|
494 |
+
if x is not NotImplemented:
|
495 |
+
return not x
|
496 |
+
return NotImplemented
|
497 |
+
|
498 |
+
def __hash__(self) -> int:
|
499 |
+
return hash(str(self))
|
500 |
+
|
501 |
+
def _promote(self, type_or_prototype: Optional[Type[Any]]) -> None:
|
502 |
+
"""
|
503 |
+
Retypes a node.
|
504 |
+
This should only be used in rare circumstances, where you want to dynamically change
|
505 |
+
the runtime structured-type of a DictConfig.
|
506 |
+
It will change the type and add the additional fields based on the input class or object
|
507 |
+
"""
|
508 |
+
if type_or_prototype is None:
|
509 |
+
return
|
510 |
+
if not is_structured_config(type_or_prototype):
|
511 |
+
raise ValueError(f"Expected structured config class : {type_or_prototype}")
|
512 |
+
|
513 |
+
from omegaconf import OmegaConf
|
514 |
+
|
515 |
+
proto: DictConfig = OmegaConf.structured(type_or_prototype)
|
516 |
+
object_type = proto._metadata.object_type
|
517 |
+
# remove the type to prevent assignment validation from rejecting the promotion.
|
518 |
+
proto._metadata.object_type = None
|
519 |
+
self.merge_with(proto)
|
520 |
+
# restore the type.
|
521 |
+
self._metadata.object_type = object_type
|
522 |
+
|
523 |
+
def _set_value(self, value: Any) -> None:
|
524 |
+
from omegaconf import OmegaConf
|
525 |
+
|
526 |
+
assert not isinstance(value, ValueNode)
|
527 |
+
self._validate_set(key=None, value=value)
|
528 |
+
|
529 |
+
if OmegaConf.is_none(value):
|
530 |
+
self.__dict__["_content"] = None
|
531 |
+
self._metadata.object_type = None
|
532 |
+
elif _is_interpolation(value):
|
533 |
+
self.__dict__["_content"] = value
|
534 |
+
self._metadata.object_type = None
|
535 |
+
elif value == "???":
|
536 |
+
self.__dict__["_content"] = "???"
|
537 |
+
self._metadata.object_type = None
|
538 |
+
else:
|
539 |
+
self.__dict__["_content"] = {}
|
540 |
+
if is_structured_config(value):
|
541 |
+
self._metadata.object_type = None
|
542 |
+
data = get_structured_config_data(value)
|
543 |
+
for k, v in data.items():
|
544 |
+
self.__setitem__(k, v)
|
545 |
+
self._metadata.object_type = get_type_of(value)
|
546 |
+
elif isinstance(value, DictConfig):
|
547 |
+
self._metadata.object_type = dict
|
548 |
+
for k, v in value.__dict__["_content"].items():
|
549 |
+
self.__setitem__(k, v)
|
550 |
+
self.__dict__["_metadata"] = copy.deepcopy(value._metadata)
|
551 |
+
|
552 |
+
elif isinstance(value, dict):
|
553 |
+
for k, v in value.items():
|
554 |
+
self.__setitem__(k, v)
|
555 |
+
else:
|
556 |
+
msg = f"Unsupported value type : {value}"
|
557 |
+
raise ValidationError(msg=msg) # pragma: no cover
|
558 |
+
|
559 |
+
@staticmethod
|
560 |
+
def _dict_conf_eq(d1: "DictConfig", d2: "DictConfig") -> bool:
|
561 |
+
|
562 |
+
d1_none = d1.__dict__["_content"] is None
|
563 |
+
d2_none = d2.__dict__["_content"] is None
|
564 |
+
if d1_none and d2_none:
|
565 |
+
return True
|
566 |
+
if d1_none != d2_none:
|
567 |
+
return False
|
568 |
+
|
569 |
+
assert isinstance(d1, DictConfig)
|
570 |
+
assert isinstance(d2, DictConfig)
|
571 |
+
if len(d1) != len(d2):
|
572 |
+
return False
|
573 |
+
for k, v in d1.items_ex(resolve=False):
|
574 |
+
if k not in d2.__dict__["_content"]:
|
575 |
+
return False
|
576 |
+
if not BaseContainer._item_eq(d1, k, d2, k):
|
577 |
+
return False
|
578 |
+
|
579 |
+
return True
|
omegaconf/errors.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Optional, Type
|
2 |
+
|
3 |
+
|
4 |
+
class OmegaConfBaseException(Exception):
|
5 |
+
# would ideally be typed Optional[Node]
|
6 |
+
parent_node: Any
|
7 |
+
child_node: Any
|
8 |
+
key: Any
|
9 |
+
full_key: Optional[str]
|
10 |
+
value: Any
|
11 |
+
msg: Optional[str]
|
12 |
+
cause: Optional[Exception]
|
13 |
+
object_type: Optional[Type[Any]]
|
14 |
+
object_type_str: Optional[str]
|
15 |
+
ref_type: Optional[Type[Any]]
|
16 |
+
ref_type_str: Optional[str]
|
17 |
+
|
18 |
+
_initialized: bool = False
|
19 |
+
|
20 |
+
def __init__(self, *_args: Any, **_kwargs: Any) -> None:
|
21 |
+
self.parent_node = None
|
22 |
+
self.child_node = None
|
23 |
+
self.key = None
|
24 |
+
self.full_key = None
|
25 |
+
self.value = None
|
26 |
+
self.msg = None
|
27 |
+
self.object_type = None
|
28 |
+
self.ref_type = None
|
29 |
+
|
30 |
+
|
31 |
+
class MissingMandatoryValue(OmegaConfBaseException):
|
32 |
+
"""Thrown when a variable flagged with '???' value is accessed to
|
33 |
+
indicate that the value was not set"""
|
34 |
+
|
35 |
+
|
36 |
+
class KeyValidationError(OmegaConfBaseException, ValueError):
|
37 |
+
"""
|
38 |
+
Thrown when an a key of invalid type is used
|
39 |
+
"""
|
40 |
+
|
41 |
+
|
42 |
+
class ValidationError(OmegaConfBaseException, ValueError):
|
43 |
+
"""
|
44 |
+
Thrown when a value fails validation
|
45 |
+
"""
|
46 |
+
|
47 |
+
|
48 |
+
class UnsupportedValueType(ValidationError, ValueError):
|
49 |
+
"""
|
50 |
+
Thrown when an input value is not of supported type
|
51 |
+
"""
|
52 |
+
|
53 |
+
|
54 |
+
class ReadonlyConfigError(OmegaConfBaseException):
|
55 |
+
"""
|
56 |
+
Thrown when someone tries to modify a frozen config
|
57 |
+
"""
|
58 |
+
|
59 |
+
|
60 |
+
class UnsupportedInterpolationType(OmegaConfBaseException, ValueError):
|
61 |
+
"""
|
62 |
+
Thrown when an attempt to use an unregistered interpolation is made
|
63 |
+
"""
|
64 |
+
|
65 |
+
|
66 |
+
class ConfigKeyError(OmegaConfBaseException, KeyError):
|
67 |
+
"""
|
68 |
+
Thrown from DictConfig when a regular dict access would have caused a KeyError.
|
69 |
+
"""
|
70 |
+
|
71 |
+
msg: str
|
72 |
+
|
73 |
+
def __init__(self, msg: str) -> None:
|
74 |
+
super().__init__(msg)
|
75 |
+
self.msg = msg
|
76 |
+
|
77 |
+
def __str__(self) -> str:
|
78 |
+
"""
|
79 |
+
Workaround to nasty KeyError quirk: https://bugs.python.org/issue2651
|
80 |
+
"""
|
81 |
+
return self.msg
|
82 |
+
|
83 |
+
|
84 |
+
class ConfigAttributeError(OmegaConfBaseException, AttributeError):
|
85 |
+
"""
|
86 |
+
Thrown from a config object when a regular access would have caused an AttributeError.
|
87 |
+
"""
|
88 |
+
|
89 |
+
|
90 |
+
class ConfigTypeError(OmegaConfBaseException, TypeError):
|
91 |
+
"""
|
92 |
+
Thrown from a config object when a regular access would have caused a TypeError.
|
93 |
+
"""
|
94 |
+
|
95 |
+
|
96 |
+
class ConfigIndexError(OmegaConfBaseException, IndexError):
|
97 |
+
"""
|
98 |
+
Thrown from a config object when a regular access would have caused an IndexError.
|
99 |
+
"""
|
100 |
+
|
101 |
+
|
102 |
+
class ConfigValueError(OmegaConfBaseException, ValueError):
|
103 |
+
"""
|
104 |
+
Thrown from a config object when a regular access would have caused a ValueError.
|
105 |
+
"""
|
omegaconf/listconfig.py
ADDED
@@ -0,0 +1,544 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import itertools
|
3 |
+
from typing import (
|
4 |
+
Any,
|
5 |
+
Callable,
|
6 |
+
Dict,
|
7 |
+
Iterable,
|
8 |
+
Iterator,
|
9 |
+
List,
|
10 |
+
MutableSequence,
|
11 |
+
Optional,
|
12 |
+
Tuple,
|
13 |
+
Type,
|
14 |
+
Union,
|
15 |
+
)
|
16 |
+
|
17 |
+
from ._utils import (
|
18 |
+
ValueKind,
|
19 |
+
_get_value,
|
20 |
+
format_and_raise,
|
21 |
+
get_value_kind,
|
22 |
+
is_int,
|
23 |
+
is_primitive_list,
|
24 |
+
is_structured_config,
|
25 |
+
type_str,
|
26 |
+
)
|
27 |
+
from .base import Container, ContainerMetadata, Node
|
28 |
+
from .basecontainer import BaseContainer
|
29 |
+
from .errors import (
|
30 |
+
ConfigAttributeError,
|
31 |
+
ConfigTypeError,
|
32 |
+
ConfigValueError,
|
33 |
+
KeyValidationError,
|
34 |
+
MissingMandatoryValue,
|
35 |
+
ReadonlyConfigError,
|
36 |
+
ValidationError,
|
37 |
+
)
|
38 |
+
|
39 |
+
|
40 |
+
class ListConfig(BaseContainer, MutableSequence[Any]):
|
41 |
+
|
42 |
+
_content: Union[List[Optional[Node]], None, str]
|
43 |
+
|
44 |
+
def __init__(
|
45 |
+
self,
|
46 |
+
content: Union[List[Any], Tuple[Any, ...], str, None],
|
47 |
+
key: Any = None,
|
48 |
+
parent: Optional[Container] = None,
|
49 |
+
element_type: Optional[Type[Any]] = None,
|
50 |
+
is_optional: bool = True,
|
51 |
+
ref_type: Union[Type[Any], Any] = Any,
|
52 |
+
) -> None:
|
53 |
+
try:
|
54 |
+
super().__init__(
|
55 |
+
parent=parent,
|
56 |
+
metadata=ContainerMetadata(
|
57 |
+
ref_type=ref_type,
|
58 |
+
object_type=list,
|
59 |
+
key=key,
|
60 |
+
optional=is_optional,
|
61 |
+
element_type=element_type,
|
62 |
+
key_type=int,
|
63 |
+
),
|
64 |
+
)
|
65 |
+
self.__dict__["_content"] = None
|
66 |
+
self._set_value(value=content)
|
67 |
+
except Exception as ex:
|
68 |
+
format_and_raise(node=None, key=None, value=None, cause=ex, msg=str(ex))
|
69 |
+
|
70 |
+
def _validate_get(self, key: Any, value: Any = None) -> None:
|
71 |
+
if not isinstance(key, (int, slice)):
|
72 |
+
raise KeyValidationError(
|
73 |
+
"ListConfig indices must be integers or slices, not $KEY_TYPE"
|
74 |
+
)
|
75 |
+
|
76 |
+
def _validate_set(self, key: Any, value: Any) -> None:
|
77 |
+
from omegaconf import OmegaConf
|
78 |
+
|
79 |
+
self._validate_get(key, value)
|
80 |
+
|
81 |
+
if self._get_flag("readonly"):
|
82 |
+
raise ReadonlyConfigError("ListConfig is read-only")
|
83 |
+
|
84 |
+
if 0 <= key < self.__len__():
|
85 |
+
target = self._get_node(key)
|
86 |
+
if target is not None:
|
87 |
+
if value is None and not target._is_optional():
|
88 |
+
raise ValidationError(
|
89 |
+
"$FULL_KEY is not optional and cannot be assigned None"
|
90 |
+
)
|
91 |
+
|
92 |
+
target_type = self._metadata.element_type
|
93 |
+
value_type = OmegaConf.get_type(value)
|
94 |
+
if is_structured_config(target_type):
|
95 |
+
if (
|
96 |
+
target_type is not None
|
97 |
+
and value_type is not None
|
98 |
+
and not issubclass(value_type, target_type)
|
99 |
+
):
|
100 |
+
msg = (
|
101 |
+
f"Invalid type assigned : {type_str(value_type)} is not a "
|
102 |
+
f"subclass of {type_str(target_type)}. value: {value}"
|
103 |
+
)
|
104 |
+
raise ValidationError(msg)
|
105 |
+
|
106 |
+
def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "ListConfig":
|
107 |
+
res = ListConfig(content=[])
|
108 |
+
for k, v in self.__dict__.items():
|
109 |
+
res.__dict__[k] = copy.deepcopy(v, memo=memo)
|
110 |
+
res._re_parent()
|
111 |
+
return res
|
112 |
+
|
113 |
+
# hide content while inspecting in debugger
|
114 |
+
def __dir__(self) -> Iterable[str]:
|
115 |
+
if self._is_missing() or self._is_none():
|
116 |
+
return []
|
117 |
+
return [str(x) for x in range(0, len(self))]
|
118 |
+
|
119 |
+
def __len__(self) -> int:
|
120 |
+
if self._is_none():
|
121 |
+
return 0
|
122 |
+
if self._is_missing():
|
123 |
+
return 0
|
124 |
+
assert isinstance(self.__dict__["_content"], list)
|
125 |
+
return len(self.__dict__["_content"])
|
126 |
+
|
127 |
+
def __setattr__(self, key: str, value: Any) -> None:
|
128 |
+
self._format_and_raise(
|
129 |
+
key=key,
|
130 |
+
value=value,
|
131 |
+
cause=ConfigAttributeError("ListConfig does not support attribute access"),
|
132 |
+
)
|
133 |
+
assert False
|
134 |
+
|
135 |
+
def __getattr__(self, key: str) -> Any:
|
136 |
+
if is_int(key):
|
137 |
+
return self.__getitem__(int(key))
|
138 |
+
else:
|
139 |
+
self._format_and_raise(
|
140 |
+
key=key,
|
141 |
+
value=None,
|
142 |
+
cause=ConfigAttributeError(
|
143 |
+
"ListConfig does not support attribute access"
|
144 |
+
),
|
145 |
+
)
|
146 |
+
|
147 |
+
def __getitem__(self, index: Union[int, slice]) -> Any:
|
148 |
+
try:
|
149 |
+
if self._is_missing():
|
150 |
+
raise MissingMandatoryValue("ListConfig is missing")
|
151 |
+
self._validate_get(index, None)
|
152 |
+
if self._is_none():
|
153 |
+
raise TypeError(
|
154 |
+
"ListConfig object representing None is not subscriptable"
|
155 |
+
)
|
156 |
+
|
157 |
+
assert isinstance(self.__dict__["_content"], list)
|
158 |
+
if isinstance(index, slice):
|
159 |
+
result = []
|
160 |
+
start, stop, step = self._correct_index_params(index)
|
161 |
+
for slice_idx in itertools.islice(
|
162 |
+
range(0, len(self)), start, stop, step
|
163 |
+
):
|
164 |
+
val = self._resolve_with_default(
|
165 |
+
key=slice_idx, value=self.__dict__["_content"][slice_idx]
|
166 |
+
)
|
167 |
+
result.append(val)
|
168 |
+
if index.step and index.step < 0:
|
169 |
+
result.reverse()
|
170 |
+
return result
|
171 |
+
else:
|
172 |
+
return self._resolve_with_default(
|
173 |
+
key=index, value=self.__dict__["_content"][index]
|
174 |
+
)
|
175 |
+
except Exception as e:
|
176 |
+
self._format_and_raise(key=index, value=None, cause=e)
|
177 |
+
|
178 |
+
def _correct_index_params(self, index: slice) -> Tuple[int, int, int]:
|
179 |
+
start = index.start
|
180 |
+
stop = index.stop
|
181 |
+
step = index.step
|
182 |
+
if index.start and index.start < 0:
|
183 |
+
start = self.__len__() + index.start
|
184 |
+
if index.stop and index.stop < 0:
|
185 |
+
stop = self.__len__() + index.stop
|
186 |
+
if index.step and index.step < 0:
|
187 |
+
step = abs(step)
|
188 |
+
if start and stop:
|
189 |
+
if start > stop:
|
190 |
+
start, stop = stop + 1, start + 1
|
191 |
+
else:
|
192 |
+
start = stop = 0
|
193 |
+
elif not start and stop:
|
194 |
+
start = list(range(self.__len__() - 1, stop, -step))[0]
|
195 |
+
stop = None
|
196 |
+
elif start and not stop:
|
197 |
+
stop = start + 1
|
198 |
+
start = (stop - 1) % step
|
199 |
+
else:
|
200 |
+
start = (self.__len__() - 1) % step
|
201 |
+
return start, stop, step
|
202 |
+
|
203 |
+
def _set_at_index(self, index: Union[int, slice], value: Any) -> None:
|
204 |
+
self._set_item_impl(index, value)
|
205 |
+
|
206 |
+
def __setitem__(self, index: Union[int, slice], value: Any) -> None:
|
207 |
+
try:
|
208 |
+
self._set_at_index(index, value)
|
209 |
+
except Exception as e:
|
210 |
+
self._format_and_raise(key=index, value=value, cause=e)
|
211 |
+
|
212 |
+
def append(self, item: Any) -> None:
|
213 |
+
try:
|
214 |
+
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
|
215 |
+
|
216 |
+
index = len(self)
|
217 |
+
self._validate_set(key=index, value=item)
|
218 |
+
|
219 |
+
node = _maybe_wrap(
|
220 |
+
ref_type=self.__dict__["_metadata"].element_type,
|
221 |
+
key=index,
|
222 |
+
value=item,
|
223 |
+
is_optional=OmegaConf.is_optional(item),
|
224 |
+
parent=self,
|
225 |
+
)
|
226 |
+
self.__dict__["_content"].append(node)
|
227 |
+
except Exception as e:
|
228 |
+
self._format_and_raise(key=index, value=item, cause=e)
|
229 |
+
assert False
|
230 |
+
|
231 |
+
def _update_keys(self) -> None:
|
232 |
+
for i in range(len(self)):
|
233 |
+
node = self._get_node(i)
|
234 |
+
if node is not None:
|
235 |
+
node._metadata.key = i
|
236 |
+
|
237 |
+
def insert(self, index: int, item: Any) -> None:
|
238 |
+
from omegaconf.omegaconf import OmegaConf, _maybe_wrap
|
239 |
+
|
240 |
+
try:
|
241 |
+
if self._get_flag("readonly"):
|
242 |
+
raise ReadonlyConfigError("Cannot insert into a read-only ListConfig")
|
243 |
+
if self._is_none():
|
244 |
+
raise TypeError(
|
245 |
+
"Cannot insert into ListConfig object representing None"
|
246 |
+
)
|
247 |
+
if self._is_missing():
|
248 |
+
raise MissingMandatoryValue("Cannot insert into missing ListConfig")
|
249 |
+
|
250 |
+
try:
|
251 |
+
assert isinstance(self.__dict__["_content"], list)
|
252 |
+
# insert place holder
|
253 |
+
self.__dict__["_content"].insert(index, None)
|
254 |
+
node = _maybe_wrap(
|
255 |
+
ref_type=self.__dict__["_metadata"].element_type,
|
256 |
+
key=index,
|
257 |
+
value=item,
|
258 |
+
is_optional=OmegaConf.is_optional(item),
|
259 |
+
parent=self,
|
260 |
+
)
|
261 |
+
self._validate_set(key=index, value=node)
|
262 |
+
self._set_at_index(index, node)
|
263 |
+
self._update_keys()
|
264 |
+
except Exception:
|
265 |
+
del self.__dict__["_content"][index]
|
266 |
+
self._update_keys()
|
267 |
+
raise
|
268 |
+
except Exception as e:
|
269 |
+
self._format_and_raise(key=index, value=item, cause=e)
|
270 |
+
assert False
|
271 |
+
|
272 |
+
def extend(self, lst: Iterable[Any]) -> None:
|
273 |
+
assert isinstance(lst, (tuple, list, ListConfig))
|
274 |
+
for x in lst:
|
275 |
+
self.append(x)
|
276 |
+
|
277 |
+
def remove(self, x: Any) -> None:
|
278 |
+
del self[self.index(x)]
|
279 |
+
|
280 |
+
def __delitem__(self, key: Union[int, slice]) -> None:
|
281 |
+
if self._get_flag("readonly"):
|
282 |
+
self._format_and_raise(
|
283 |
+
key=key,
|
284 |
+
value=None,
|
285 |
+
cause=ReadonlyConfigError(
|
286 |
+
"Cannot delete item from read-only ListConfig"
|
287 |
+
),
|
288 |
+
)
|
289 |
+
del self.__dict__["_content"][key]
|
290 |
+
self._update_keys()
|
291 |
+
|
292 |
+
def clear(self) -> None:
|
293 |
+
del self[:]
|
294 |
+
|
295 |
+
def index(
|
296 |
+
self, x: Any, start: Optional[int] = None, end: Optional[int] = None
|
297 |
+
) -> int:
|
298 |
+
if start is None:
|
299 |
+
start = 0
|
300 |
+
if end is None:
|
301 |
+
end = len(self)
|
302 |
+
assert start >= 0
|
303 |
+
assert end <= len(self)
|
304 |
+
found_idx = -1
|
305 |
+
for idx in range(start, end):
|
306 |
+
item = self[idx]
|
307 |
+
if x == item:
|
308 |
+
found_idx = idx
|
309 |
+
break
|
310 |
+
if found_idx != -1:
|
311 |
+
return found_idx
|
312 |
+
else:
|
313 |
+
self._format_and_raise(
|
314 |
+
key=None,
|
315 |
+
value=None,
|
316 |
+
cause=ConfigValueError("Item not found in ListConfig"),
|
317 |
+
)
|
318 |
+
assert False
|
319 |
+
|
320 |
+
def count(self, x: Any) -> int:
|
321 |
+
c = 0
|
322 |
+
for item in self:
|
323 |
+
if item == x:
|
324 |
+
c = c + 1
|
325 |
+
return c
|
326 |
+
|
327 |
+
def copy(self) -> "ListConfig":
|
328 |
+
return copy.copy(self)
|
329 |
+
|
330 |
+
def _get_node(
|
331 |
+
self, key: Union[int, slice], validate_access: bool = True
|
332 |
+
) -> Optional[Node]:
|
333 |
+
try:
|
334 |
+
if self._is_none():
|
335 |
+
raise TypeError(
|
336 |
+
"Cannot get_node from a ListConfig object representing None"
|
337 |
+
)
|
338 |
+
if self._is_missing():
|
339 |
+
raise MissingMandatoryValue("Cannot get_node from a missing ListConfig")
|
340 |
+
assert isinstance(self.__dict__["_content"], list)
|
341 |
+
if validate_access:
|
342 |
+
self._validate_get(key)
|
343 |
+
return self.__dict__["_content"][key] # type: ignore
|
344 |
+
except (IndexError, TypeError, MissingMandatoryValue, KeyValidationError) as e:
|
345 |
+
if validate_access:
|
346 |
+
self._format_and_raise(key=key, value=None, cause=e)
|
347 |
+
assert False
|
348 |
+
else:
|
349 |
+
return None
|
350 |
+
|
351 |
+
def get(self, index: int, default_value: Any = None) -> Any:
|
352 |
+
try:
|
353 |
+
if self._is_none():
|
354 |
+
raise TypeError("Cannot get from a ListConfig object representing None")
|
355 |
+
if self._is_missing():
|
356 |
+
raise MissingMandatoryValue("Cannot get from a missing ListConfig")
|
357 |
+
self._validate_get(index, None)
|
358 |
+
assert isinstance(self.__dict__["_content"], list)
|
359 |
+
return self._resolve_with_default(
|
360 |
+
key=index,
|
361 |
+
value=self.__dict__["_content"][index],
|
362 |
+
default_value=default_value,
|
363 |
+
)
|
364 |
+
except Exception as e:
|
365 |
+
self._format_and_raise(key=index, value=None, cause=e)
|
366 |
+
assert False
|
367 |
+
|
368 |
+
def pop(self, index: int = -1) -> Any:
|
369 |
+
try:
|
370 |
+
if self._get_flag("readonly"):
|
371 |
+
raise ReadonlyConfigError("Cannot pop from read-only ListConfig")
|
372 |
+
if self._is_none():
|
373 |
+
raise TypeError("Cannot pop from a ListConfig object representing None")
|
374 |
+
if self._is_missing():
|
375 |
+
raise MissingMandatoryValue("Cannot pop from a missing ListConfig")
|
376 |
+
|
377 |
+
assert isinstance(self.__dict__["_content"], list)
|
378 |
+
ret = self._resolve_with_default(
|
379 |
+
key=index, value=self._get_node(index), default_value=None
|
380 |
+
)
|
381 |
+
del self.__dict__["_content"][index]
|
382 |
+
self._update_keys()
|
383 |
+
return ret
|
384 |
+
except KeyValidationError as e:
|
385 |
+
self._format_and_raise(
|
386 |
+
key=index, value=None, cause=e, type_override=ConfigTypeError
|
387 |
+
)
|
388 |
+
assert False
|
389 |
+
except Exception as e:
|
390 |
+
self._format_and_raise(key=index, value=None, cause=e)
|
391 |
+
assert False
|
392 |
+
|
393 |
+
def sort(
|
394 |
+
self, key: Optional[Callable[[Any], Any]] = None, reverse: bool = False
|
395 |
+
) -> None:
|
396 |
+
try:
|
397 |
+
if self._get_flag("readonly"):
|
398 |
+
raise ReadonlyConfigError("Cannot sort a read-only ListConfig")
|
399 |
+
if self._is_none():
|
400 |
+
raise TypeError("Cannot sort a ListConfig object representing None")
|
401 |
+
if self._is_missing():
|
402 |
+
raise MissingMandatoryValue("Cannot sort a missing ListConfig")
|
403 |
+
|
404 |
+
if key is None:
|
405 |
+
|
406 |
+
def key1(x: Any) -> Any:
|
407 |
+
return x._value()
|
408 |
+
|
409 |
+
else:
|
410 |
+
|
411 |
+
def key1(x: Any) -> Any:
|
412 |
+
return key(x._value()) # type: ignore
|
413 |
+
|
414 |
+
assert isinstance(self.__dict__["_content"], list)
|
415 |
+
self.__dict__["_content"].sort(key=key1, reverse=reverse)
|
416 |
+
|
417 |
+
except Exception as e:
|
418 |
+
self._format_and_raise(key=None, value=None, cause=e)
|
419 |
+
assert False
|
420 |
+
|
421 |
+
def __eq__(self, other: Any) -> bool:
|
422 |
+
if isinstance(other, (list, tuple)) or other is None:
|
423 |
+
other = ListConfig(other)
|
424 |
+
return ListConfig._list_eq(self, other)
|
425 |
+
if other is None or isinstance(other, ListConfig):
|
426 |
+
return ListConfig._list_eq(self, other)
|
427 |
+
return NotImplemented
|
428 |
+
|
429 |
+
def __ne__(self, other: Any) -> bool:
|
430 |
+
x = self.__eq__(other)
|
431 |
+
if x is not NotImplemented:
|
432 |
+
return not x
|
433 |
+
return NotImplemented
|
434 |
+
|
435 |
+
def __hash__(self) -> int:
|
436 |
+
return hash(str(self))
|
437 |
+
|
438 |
+
def __iter__(self) -> Iterator[Any]:
|
439 |
+
return self._iter_ex(resolve=True)
|
440 |
+
|
441 |
+
def _iter_ex(self, resolve: bool) -> Iterator[Any]:
|
442 |
+
try:
|
443 |
+
if self._is_none():
|
444 |
+
raise TypeError("Cannot iterate a ListConfig object representing None")
|
445 |
+
if self._is_missing():
|
446 |
+
raise MissingMandatoryValue("Cannot iterate a missing ListConfig")
|
447 |
+
|
448 |
+
class MyItems(Iterator[Any]):
|
449 |
+
def __init__(self, lst: ListConfig) -> None:
|
450 |
+
self.lst = lst
|
451 |
+
self.index = 0
|
452 |
+
|
453 |
+
def __next__(self) -> Any:
|
454 |
+
if self.index == len(self.lst):
|
455 |
+
raise StopIteration()
|
456 |
+
if resolve:
|
457 |
+
v = self.lst[self.index]
|
458 |
+
else:
|
459 |
+
v = self.lst.__dict__["_content"][self.index]
|
460 |
+
if v is not None:
|
461 |
+
v = _get_value(v)
|
462 |
+
self.index = self.index + 1
|
463 |
+
return v
|
464 |
+
|
465 |
+
assert isinstance(self.__dict__["_content"], list)
|
466 |
+
return MyItems(self)
|
467 |
+
except (ReadonlyConfigError, TypeError, MissingMandatoryValue) as e:
|
468 |
+
self._format_and_raise(key=None, value=None, cause=e)
|
469 |
+
assert False
|
470 |
+
|
471 |
+
def __add__(self, other: Union[List[Any], "ListConfig"]) -> "ListConfig":
|
472 |
+
# res is sharing this list's parent to allow interpolation to work as expected
|
473 |
+
res = ListConfig(parent=self._get_parent(), content=[])
|
474 |
+
res.extend(self)
|
475 |
+
res.extend(other)
|
476 |
+
return res
|
477 |
+
|
478 |
+
def __iadd__(self, other: Iterable[Any]) -> "ListConfig":
|
479 |
+
self.extend(other)
|
480 |
+
return self
|
481 |
+
|
482 |
+
def __contains__(self, item: Any) -> bool:
|
483 |
+
for x in iter(self):
|
484 |
+
if x == item:
|
485 |
+
return True
|
486 |
+
return False
|
487 |
+
|
488 |
+
def _set_value(self, value: Any) -> None:
|
489 |
+
from omegaconf import OmegaConf
|
490 |
+
|
491 |
+
if OmegaConf.is_none(value):
|
492 |
+
if not self._is_optional():
|
493 |
+
raise ValidationError(
|
494 |
+
"Non optional ListConfig cannot be constructed from None"
|
495 |
+
)
|
496 |
+
self.__dict__["_content"] = None
|
497 |
+
elif get_value_kind(value) == ValueKind.MANDATORY_MISSING:
|
498 |
+
self.__dict__["_content"] = "???"
|
499 |
+
elif get_value_kind(value) in (
|
500 |
+
ValueKind.INTERPOLATION,
|
501 |
+
ValueKind.STR_INTERPOLATION,
|
502 |
+
):
|
503 |
+
self.__dict__["_content"] = value
|
504 |
+
else:
|
505 |
+
if not (is_primitive_list(value) or isinstance(value, ListConfig)):
|
506 |
+
type_ = type(value)
|
507 |
+
msg = (
|
508 |
+
f"Invalid value assigned : {type_.__name__} is not a "
|
509 |
+
f"subclass of ListConfig or list."
|
510 |
+
)
|
511 |
+
raise ValidationError(msg)
|
512 |
+
self.__dict__["_content"] = []
|
513 |
+
if isinstance(value, ListConfig):
|
514 |
+
self.__dict__["_metadata"] = copy.deepcopy(value._metadata)
|
515 |
+
self.__dict__["_metadata"].flags = {}
|
516 |
+
for item in value._iter_ex(resolve=False):
|
517 |
+
self.append(item)
|
518 |
+
self.__dict__["_metadata"].flags = copy.deepcopy(value._metadata.flags)
|
519 |
+
elif is_primitive_list(value):
|
520 |
+
for item in value:
|
521 |
+
self.append(item)
|
522 |
+
|
523 |
+
if isinstance(value, ListConfig):
|
524 |
+
self.__dict__["_metadata"].flags = value._metadata.flags
|
525 |
+
|
526 |
+
@staticmethod
|
527 |
+
def _list_eq(l1: Optional["ListConfig"], l2: Optional["ListConfig"]) -> bool:
|
528 |
+
|
529 |
+
l1_none = l1.__dict__["_content"] is None
|
530 |
+
l2_none = l2.__dict__["_content"] is None
|
531 |
+
if l1_none and l2_none:
|
532 |
+
return True
|
533 |
+
if l1_none != l2_none:
|
534 |
+
return False
|
535 |
+
|
536 |
+
assert isinstance(l1, ListConfig)
|
537 |
+
assert isinstance(l2, ListConfig)
|
538 |
+
if len(l1) != len(l2):
|
539 |
+
return False
|
540 |
+
for i in range(len(l1)):
|
541 |
+
if not BaseContainer._item_eq(l1, i, l2, i):
|
542 |
+
return False
|
543 |
+
|
544 |
+
return True
|
omegaconf/nodes.py
ADDED
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import math
|
3 |
+
import sys
|
4 |
+
from enum import Enum
|
5 |
+
from typing import Any, Dict, Optional, Type, Union
|
6 |
+
|
7 |
+
from omegaconf._utils import _is_interpolation, get_type_of, is_primitive_container
|
8 |
+
from omegaconf.base import Container, Metadata, Node
|
9 |
+
from omegaconf.errors import (
|
10 |
+
MissingMandatoryValue,
|
11 |
+
ReadonlyConfigError,
|
12 |
+
UnsupportedValueType,
|
13 |
+
ValidationError,
|
14 |
+
)
|
15 |
+
|
16 |
+
|
17 |
+
class ValueNode(Node):
|
18 |
+
_val: Any
|
19 |
+
|
20 |
+
def __init__(self, parent: Optional[Container], value: Any, metadata: Metadata):
|
21 |
+
from omegaconf import read_write
|
22 |
+
|
23 |
+
super().__init__(parent=parent, metadata=metadata)
|
24 |
+
with read_write(self):
|
25 |
+
self._set_value(value)
|
26 |
+
|
27 |
+
def _value(self) -> Any:
|
28 |
+
return self._val
|
29 |
+
|
30 |
+
def _set_value(self, value: Any) -> None:
|
31 |
+
from ._utils import ValueKind, get_value_kind
|
32 |
+
|
33 |
+
if self._get_flag("readonly"):
|
34 |
+
raise ReadonlyConfigError("Cannot set value of read-only config node")
|
35 |
+
|
36 |
+
if isinstance(value, str) and get_value_kind(value) in (
|
37 |
+
ValueKind.INTERPOLATION,
|
38 |
+
ValueKind.STR_INTERPOLATION,
|
39 |
+
ValueKind.MANDATORY_MISSING,
|
40 |
+
):
|
41 |
+
self._val = value
|
42 |
+
else:
|
43 |
+
if not self._metadata.optional and value is None:
|
44 |
+
raise ValidationError("Non optional field cannot be assigned None")
|
45 |
+
self._val = self.validate_and_convert(value)
|
46 |
+
|
47 |
+
def validate_and_convert(self, value: Any) -> Any:
|
48 |
+
"""
|
49 |
+
Validates input and converts to canonical form
|
50 |
+
:param value: input value
|
51 |
+
:return: converted value ("100" may be converted to 100 for example)
|
52 |
+
"""
|
53 |
+
return value
|
54 |
+
|
55 |
+
def __str__(self) -> str:
|
56 |
+
return str(self._val)
|
57 |
+
|
58 |
+
def __repr__(self) -> str:
|
59 |
+
return repr(self._val) if hasattr(self, "_val") else "__INVALID__"
|
60 |
+
|
61 |
+
def __eq__(self, other: Any) -> bool:
|
62 |
+
if isinstance(other, AnyNode):
|
63 |
+
return self._val == other._val # type: ignore
|
64 |
+
else:
|
65 |
+
return self._val == other # type: ignore
|
66 |
+
|
67 |
+
def __ne__(self, other: Any) -> bool:
|
68 |
+
x = self.__eq__(other)
|
69 |
+
assert x is not NotImplemented
|
70 |
+
return not x
|
71 |
+
|
72 |
+
def __hash__(self) -> int:
|
73 |
+
return hash(self._val)
|
74 |
+
|
75 |
+
def _deepcopy_impl(self, res: Any, memo: Optional[Dict[int, Any]] = {}) -> None:
|
76 |
+
res.__dict__ = copy.deepcopy(self.__dict__, memo=memo)
|
77 |
+
|
78 |
+
def _is_none(self) -> bool:
|
79 |
+
if self._is_interpolation():
|
80 |
+
node = self._dereference_node(
|
81 |
+
throw_on_resolution_failure=False, throw_on_missing=False
|
82 |
+
)
|
83 |
+
if node is None:
|
84 |
+
# missing or resolution failure
|
85 |
+
return False
|
86 |
+
else:
|
87 |
+
node = self
|
88 |
+
return node._value() is None
|
89 |
+
|
90 |
+
def _is_optional(self) -> bool:
|
91 |
+
node = self._dereference_node()
|
92 |
+
assert node is not None
|
93 |
+
return node._metadata.optional
|
94 |
+
|
95 |
+
def _is_missing(self) -> bool:
|
96 |
+
try:
|
97 |
+
if self._is_interpolation():
|
98 |
+
node = self._dereference_node(
|
99 |
+
throw_on_resolution_failure=False, throw_on_missing=True
|
100 |
+
)
|
101 |
+
if node is None:
|
102 |
+
# resolution failure
|
103 |
+
return False
|
104 |
+
else:
|
105 |
+
node = self
|
106 |
+
|
107 |
+
assert node is not None
|
108 |
+
if isinstance(node, Container):
|
109 |
+
ret = node._is_missing()
|
110 |
+
else:
|
111 |
+
ret = node._value() == "???"
|
112 |
+
except MissingMandatoryValue:
|
113 |
+
ret = True
|
114 |
+
assert isinstance(ret, bool)
|
115 |
+
return ret
|
116 |
+
|
117 |
+
def _is_interpolation(self) -> bool:
|
118 |
+
return _is_interpolation(self._value())
|
119 |
+
|
120 |
+
def _get_full_key(self, key: Union[str, Enum, int, None]) -> str:
|
121 |
+
parent = self._get_parent()
|
122 |
+
if parent is None:
|
123 |
+
if self._metadata.key is None:
|
124 |
+
return ""
|
125 |
+
else:
|
126 |
+
return str(self._metadata.key)
|
127 |
+
else:
|
128 |
+
return parent._get_full_key(self._metadata.key)
|
129 |
+
|
130 |
+
|
131 |
+
class AnyNode(ValueNode):
|
132 |
+
def __init__(
|
133 |
+
self,
|
134 |
+
value: Any = None,
|
135 |
+
key: Any = None,
|
136 |
+
parent: Optional[Container] = None,
|
137 |
+
is_optional: bool = True,
|
138 |
+
):
|
139 |
+
super().__init__(
|
140 |
+
parent=parent,
|
141 |
+
value=value,
|
142 |
+
metadata=Metadata(
|
143 |
+
ref_type=Any, object_type=None, key=key, optional=is_optional # type: ignore
|
144 |
+
),
|
145 |
+
)
|
146 |
+
|
147 |
+
def validate_and_convert(self, value: Any) -> Any:
|
148 |
+
from ._utils import is_primitive_type
|
149 |
+
|
150 |
+
if not is_primitive_type(value):
|
151 |
+
t = get_type_of(value)
|
152 |
+
raise UnsupportedValueType(
|
153 |
+
f"Value '{t.__name__}' is not a supported primitive type"
|
154 |
+
)
|
155 |
+
return value
|
156 |
+
|
157 |
+
def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "AnyNode":
|
158 |
+
res = AnyNode()
|
159 |
+
self._deepcopy_impl(res, memo)
|
160 |
+
return res
|
161 |
+
|
162 |
+
|
163 |
+
class StringNode(ValueNode):
|
164 |
+
def __init__(
|
165 |
+
self,
|
166 |
+
value: Any = None,
|
167 |
+
key: Any = None,
|
168 |
+
parent: Optional[Container] = None,
|
169 |
+
is_optional: bool = True,
|
170 |
+
):
|
171 |
+
super().__init__(
|
172 |
+
parent=parent,
|
173 |
+
value=value,
|
174 |
+
metadata=Metadata(
|
175 |
+
key=key, optional=is_optional, ref_type=str, object_type=str
|
176 |
+
),
|
177 |
+
)
|
178 |
+
|
179 |
+
def validate_and_convert(self, value: Any) -> Optional[str]:
|
180 |
+
from omegaconf import OmegaConf
|
181 |
+
|
182 |
+
if OmegaConf.is_config(value) or is_primitive_container(value):
|
183 |
+
raise ValidationError("Cannot convert '$VALUE_TYPE' to string : '$VALUE'")
|
184 |
+
return str(value) if value is not None else None
|
185 |
+
|
186 |
+
def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "StringNode":
|
187 |
+
res = StringNode()
|
188 |
+
self._deepcopy_impl(res, memo)
|
189 |
+
return res
|
190 |
+
|
191 |
+
|
192 |
+
class IntegerNode(ValueNode):
|
193 |
+
def __init__(
|
194 |
+
self,
|
195 |
+
value: Any = None,
|
196 |
+
key: Any = None,
|
197 |
+
parent: Optional[Container] = None,
|
198 |
+
is_optional: bool = True,
|
199 |
+
):
|
200 |
+
super().__init__(
|
201 |
+
parent=parent,
|
202 |
+
value=value,
|
203 |
+
metadata=Metadata(
|
204 |
+
key=key, optional=is_optional, ref_type=int, object_type=int
|
205 |
+
),
|
206 |
+
)
|
207 |
+
|
208 |
+
def validate_and_convert(self, value: Any) -> Optional[int]:
|
209 |
+
try:
|
210 |
+
if value is None:
|
211 |
+
val = None
|
212 |
+
elif type(value) in (str, int):
|
213 |
+
val = int(value)
|
214 |
+
else:
|
215 |
+
raise ValueError()
|
216 |
+
except ValueError:
|
217 |
+
raise ValidationError("Value '$VALUE' could not be converted to Integer")
|
218 |
+
return val
|
219 |
+
|
220 |
+
def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "IntegerNode":
|
221 |
+
res = IntegerNode()
|
222 |
+
self._deepcopy_impl(res, memo)
|
223 |
+
return res
|
224 |
+
|
225 |
+
|
226 |
+
class FloatNode(ValueNode):
|
227 |
+
def __init__(
|
228 |
+
self,
|
229 |
+
value: Any = None,
|
230 |
+
key: Any = None,
|
231 |
+
parent: Optional[Container] = None,
|
232 |
+
is_optional: bool = True,
|
233 |
+
):
|
234 |
+
super().__init__(
|
235 |
+
parent=parent,
|
236 |
+
value=value,
|
237 |
+
metadata=Metadata(
|
238 |
+
key=key, optional=is_optional, ref_type=float, object_type=float
|
239 |
+
),
|
240 |
+
)
|
241 |
+
|
242 |
+
def validate_and_convert(self, value: Any) -> Optional[float]:
|
243 |
+
if value is None:
|
244 |
+
return None
|
245 |
+
try:
|
246 |
+
if type(value) in (float, str, int):
|
247 |
+
return float(value)
|
248 |
+
else:
|
249 |
+
raise ValueError()
|
250 |
+
except ValueError:
|
251 |
+
raise ValidationError("Value '$VALUE' could not be converted to Float")
|
252 |
+
|
253 |
+
def __eq__(self, other: Any) -> bool:
|
254 |
+
if isinstance(other, ValueNode):
|
255 |
+
other_val = other._val
|
256 |
+
else:
|
257 |
+
other_val = other
|
258 |
+
if self._val is None and other is None:
|
259 |
+
return True
|
260 |
+
if self._val is None and other is not None:
|
261 |
+
return False
|
262 |
+
if self._val is not None and other is None:
|
263 |
+
return False
|
264 |
+
nan1 = math.isnan(self._val) if isinstance(self._val, float) else False
|
265 |
+
nan2 = math.isnan(other_val) if isinstance(other_val, float) else False
|
266 |
+
return self._val == other_val or (nan1 and nan2)
|
267 |
+
|
268 |
+
def __hash__(self) -> int:
|
269 |
+
return hash(self._val)
|
270 |
+
|
271 |
+
def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "FloatNode":
|
272 |
+
res = FloatNode()
|
273 |
+
self._deepcopy_impl(res, memo)
|
274 |
+
return res
|
275 |
+
|
276 |
+
|
277 |
+
class BooleanNode(ValueNode):
|
278 |
+
def __init__(
|
279 |
+
self,
|
280 |
+
value: Any = None,
|
281 |
+
key: Any = None,
|
282 |
+
parent: Optional[Container] = None,
|
283 |
+
is_optional: bool = True,
|
284 |
+
):
|
285 |
+
super().__init__(
|
286 |
+
parent=parent,
|
287 |
+
value=value,
|
288 |
+
metadata=Metadata(
|
289 |
+
key=key, optional=is_optional, ref_type=bool, object_type=bool
|
290 |
+
),
|
291 |
+
)
|
292 |
+
|
293 |
+
def validate_and_convert(self, value: Any) -> Optional[bool]:
|
294 |
+
if isinstance(value, bool):
|
295 |
+
return value
|
296 |
+
if isinstance(value, int):
|
297 |
+
return value != 0
|
298 |
+
elif value is None:
|
299 |
+
return None
|
300 |
+
elif isinstance(value, str):
|
301 |
+
try:
|
302 |
+
return self.validate_and_convert(int(value))
|
303 |
+
except ValueError as e:
|
304 |
+
if value.lower() in ("yes", "y", "on", "true"):
|
305 |
+
return True
|
306 |
+
elif value.lower() in ("no", "n", "off", "false"):
|
307 |
+
return False
|
308 |
+
else:
|
309 |
+
raise ValidationError(
|
310 |
+
"Value '$VALUE' is not a valid bool (type $VALUE_TYPE)"
|
311 |
+
).with_traceback(sys.exc_info()[2]) from e
|
312 |
+
else:
|
313 |
+
raise ValidationError(
|
314 |
+
"Value '$VALUE' is not a valid bool (type $VALUE_TYPE)"
|
315 |
+
)
|
316 |
+
|
317 |
+
def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "BooleanNode":
|
318 |
+
res = BooleanNode()
|
319 |
+
self._deepcopy_impl(res, memo)
|
320 |
+
return res
|
321 |
+
|
322 |
+
|
323 |
+
class EnumNode(ValueNode): # lgtm [py/missing-equals] : Intentional.
|
324 |
+
"""
|
325 |
+
NOTE: EnumNode is serialized to yaml as a string ("Color.BLUE"), not as a fully qualified yaml type.
|
326 |
+
this means serialization to YAML of a typed config (with EnumNode) will not retain the type of the Enum
|
327 |
+
when loaded.
|
328 |
+
This is intentional, Please open an issue against OmegaConf if you wish to discuss this decision.
|
329 |
+
"""
|
330 |
+
|
331 |
+
def __init__(
|
332 |
+
self,
|
333 |
+
enum_type: Type[Enum],
|
334 |
+
value: Optional[Union[Enum, str]] = None,
|
335 |
+
key: Any = None,
|
336 |
+
parent: Optional[Container] = None,
|
337 |
+
is_optional: bool = True,
|
338 |
+
):
|
339 |
+
if not isinstance(enum_type, type) or not issubclass(enum_type, Enum):
|
340 |
+
raise ValidationError(
|
341 |
+
f"EnumNode can only operate on Enum subclasses ({enum_type})"
|
342 |
+
)
|
343 |
+
self.fields: Dict[str, str] = {}
|
344 |
+
self.enum_type: Type[Enum] = enum_type
|
345 |
+
for name, constant in enum_type.__members__.items():
|
346 |
+
self.fields[name] = constant.value
|
347 |
+
super().__init__(
|
348 |
+
parent=parent,
|
349 |
+
value=value,
|
350 |
+
metadata=Metadata(
|
351 |
+
key=key, optional=is_optional, ref_type=enum_type, object_type=enum_type
|
352 |
+
),
|
353 |
+
)
|
354 |
+
|
355 |
+
def validate_and_convert(self, value: Any) -> Optional[Enum]:
|
356 |
+
return self.validate_and_convert_to_enum(enum_type=self.enum_type, value=value)
|
357 |
+
|
358 |
+
@staticmethod
|
359 |
+
def validate_and_convert_to_enum(
|
360 |
+
enum_type: Type[Enum], value: Any
|
361 |
+
) -> Optional[Enum]:
|
362 |
+
if value is None:
|
363 |
+
return None
|
364 |
+
|
365 |
+
if not isinstance(value, (str, int)) and not isinstance(value, enum_type):
|
366 |
+
raise ValidationError(
|
367 |
+
f"Value $VALUE ($VALUE_TYPE) is not a valid input for {enum_type}"
|
368 |
+
)
|
369 |
+
|
370 |
+
if isinstance(value, enum_type):
|
371 |
+
return value
|
372 |
+
|
373 |
+
try:
|
374 |
+
if isinstance(value, (float, bool)):
|
375 |
+
raise ValueError
|
376 |
+
|
377 |
+
if isinstance(value, int):
|
378 |
+
return enum_type(value)
|
379 |
+
|
380 |
+
if isinstance(value, str):
|
381 |
+
prefix = f"{enum_type.__name__}."
|
382 |
+
if value.startswith(prefix):
|
383 |
+
value = value[len(prefix) :]
|
384 |
+
return enum_type[value]
|
385 |
+
|
386 |
+
assert False
|
387 |
+
|
388 |
+
except (ValueError, KeyError) as e:
|
389 |
+
valid = ", ".join([x for x in enum_type.__members__.keys()])
|
390 |
+
raise ValidationError(
|
391 |
+
f"Invalid value '$VALUE', expected one of [{valid}]"
|
392 |
+
).with_traceback(sys.exc_info()[2]) from e
|
393 |
+
|
394 |
+
def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "EnumNode":
|
395 |
+
res = EnumNode(enum_type=self.enum_type)
|
396 |
+
self._deepcopy_impl(res, memo)
|
397 |
+
return res
|
omegaconf/omegaconf.py
ADDED
@@ -0,0 +1,813 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""OmegaConf module"""
|
2 |
+
import copy
|
3 |
+
import io
|
4 |
+
import os
|
5 |
+
import pathlib
|
6 |
+
import re
|
7 |
+
import sys
|
8 |
+
import warnings
|
9 |
+
from collections import defaultdict
|
10 |
+
from contextlib import contextmanager
|
11 |
+
from enum import Enum
|
12 |
+
from textwrap import dedent
|
13 |
+
from typing import (
|
14 |
+
IO,
|
15 |
+
Any,
|
16 |
+
Callable,
|
17 |
+
Dict,
|
18 |
+
Generator,
|
19 |
+
List,
|
20 |
+
Match,
|
21 |
+
Optional,
|
22 |
+
Tuple,
|
23 |
+
Type,
|
24 |
+
Union,
|
25 |
+
overload,
|
26 |
+
)
|
27 |
+
|
28 |
+
import yaml
|
29 |
+
from typing_extensions import Protocol
|
30 |
+
|
31 |
+
from . import DictConfig, ListConfig
|
32 |
+
from ._utils import (
|
33 |
+
_ensure_container,
|
34 |
+
_get_value,
|
35 |
+
decode_primitive,
|
36 |
+
format_and_raise,
|
37 |
+
get_dict_key_value_types,
|
38 |
+
get_list_element_type,
|
39 |
+
get_omega_conf_dumper,
|
40 |
+
get_type_of,
|
41 |
+
is_attr_class,
|
42 |
+
is_dataclass,
|
43 |
+
is_dict_annotation,
|
44 |
+
is_int,
|
45 |
+
is_list_annotation,
|
46 |
+
is_primitive_container,
|
47 |
+
is_primitive_dict,
|
48 |
+
is_primitive_list,
|
49 |
+
is_structured_config,
|
50 |
+
is_tuple_annotation,
|
51 |
+
type_str,
|
52 |
+
)
|
53 |
+
from .base import Container, Node
|
54 |
+
from .basecontainer import BaseContainer
|
55 |
+
from .errors import (
|
56 |
+
MissingMandatoryValue,
|
57 |
+
OmegaConfBaseException,
|
58 |
+
UnsupportedInterpolationType,
|
59 |
+
ValidationError,
|
60 |
+
)
|
61 |
+
from .nodes import (
|
62 |
+
AnyNode,
|
63 |
+
BooleanNode,
|
64 |
+
EnumNode,
|
65 |
+
FloatNode,
|
66 |
+
IntegerNode,
|
67 |
+
StringNode,
|
68 |
+
ValueNode,
|
69 |
+
)
|
70 |
+
|
71 |
+
MISSING: Any = "???"
|
72 |
+
|
73 |
+
# A marker used in OmegaConf.create() to differentiate between creating an empty {} DictConfig
|
74 |
+
# and creating a DictConfig with None content.
|
75 |
+
_EMPTY_MARKER_ = object()
|
76 |
+
|
77 |
+
|
78 |
+
def II(interpolation: str) -> Any:
|
79 |
+
"""
|
80 |
+
Equivalent to ${interpolation}
|
81 |
+
:param interpolation:
|
82 |
+
:return: input ${node} with type Any
|
83 |
+
"""
|
84 |
+
return "${" + interpolation + "}"
|
85 |
+
|
86 |
+
|
87 |
+
def SI(interpolation: str) -> Any:
|
88 |
+
"""
|
89 |
+
Use this for String interpolation, for example "http://${host}:${port}"
|
90 |
+
:param interpolation: interpolation string
|
91 |
+
:return: input interpolation with type Any
|
92 |
+
"""
|
93 |
+
return interpolation
|
94 |
+
|
95 |
+
|
96 |
+
class Resolver0(Protocol):
|
97 |
+
def __call__(self) -> Any:
|
98 |
+
...
|
99 |
+
|
100 |
+
|
101 |
+
class Resolver1(Protocol):
|
102 |
+
def __call__(self, __x1: str) -> Any:
|
103 |
+
...
|
104 |
+
|
105 |
+
|
106 |
+
class Resolver2(Protocol):
|
107 |
+
def __call__(self, __x1: str, __x2: str) -> Any:
|
108 |
+
...
|
109 |
+
|
110 |
+
|
111 |
+
class Resolver3(Protocol):
|
112 |
+
def __call__(self, __x1: str, __x2: str, __x3: str) -> Any:
|
113 |
+
...
|
114 |
+
|
115 |
+
|
116 |
+
Resolver = Union[Resolver0, Resolver1, Resolver2, Resolver3]
|
117 |
+
|
118 |
+
|
119 |
+
def register_default_resolvers() -> None:
|
120 |
+
def env(key: str, default: Optional[str] = None) -> Any:
|
121 |
+
try:
|
122 |
+
return decode_primitive(os.environ[key])
|
123 |
+
except KeyError:
|
124 |
+
if default is not None:
|
125 |
+
return decode_primitive(default)
|
126 |
+
else:
|
127 |
+
raise ValidationError(f"Environment variable '{key}' not found")
|
128 |
+
|
129 |
+
OmegaConf.register_resolver("env", env)
|
130 |
+
|
131 |
+
|
132 |
+
class OmegaConf:
|
133 |
+
"""OmegaConf primary class"""
|
134 |
+
|
135 |
+
def __init__(self) -> None:
|
136 |
+
raise NotImplementedError("Use one of the static construction functions")
|
137 |
+
|
138 |
+
@staticmethod
|
139 |
+
def structured(obj: Any, parent: Optional[BaseContainer] = None) -> Any:
|
140 |
+
return OmegaConf.create(obj, parent)
|
141 |
+
|
142 |
+
@staticmethod
|
143 |
+
@overload
|
144 |
+
def create(
|
145 |
+
obj: str, parent: Optional[BaseContainer] = None
|
146 |
+
) -> Union[DictConfig, ListConfig]:
|
147 |
+
...
|
148 |
+
|
149 |
+
@staticmethod
|
150 |
+
@overload
|
151 |
+
def create(
|
152 |
+
obj: Union[List[Any], Tuple[Any, ...]], parent: Optional[BaseContainer] = None
|
153 |
+
) -> ListConfig:
|
154 |
+
...
|
155 |
+
|
156 |
+
@staticmethod
|
157 |
+
@overload
|
158 |
+
def create(obj: DictConfig, parent: Optional[BaseContainer] = None) -> DictConfig:
|
159 |
+
...
|
160 |
+
|
161 |
+
@staticmethod
|
162 |
+
@overload
|
163 |
+
def create(obj: ListConfig, parent: Optional[BaseContainer] = None) -> ListConfig:
|
164 |
+
...
|
165 |
+
|
166 |
+
@staticmethod
|
167 |
+
@overload
|
168 |
+
def create(
|
169 |
+
obj: Union[Dict[str, Any], None] = None, parent: Optional[BaseContainer] = None
|
170 |
+
) -> DictConfig:
|
171 |
+
...
|
172 |
+
|
173 |
+
@staticmethod
|
174 |
+
def create( # noqa F811
|
175 |
+
obj: Any = _EMPTY_MARKER_, parent: Optional[BaseContainer] = None
|
176 |
+
) -> Union[DictConfig, ListConfig]:
|
177 |
+
return OmegaConf._create_impl(obj=obj, parent=parent)
|
178 |
+
|
179 |
+
@staticmethod
|
180 |
+
def _create_impl( # noqa F811
|
181 |
+
obj: Any = _EMPTY_MARKER_, parent: Optional[BaseContainer] = None
|
182 |
+
) -> Union[DictConfig, ListConfig]:
|
183 |
+
try:
|
184 |
+
from ._utils import get_yaml_loader
|
185 |
+
from .dictconfig import DictConfig
|
186 |
+
from .listconfig import ListConfig
|
187 |
+
|
188 |
+
if obj is _EMPTY_MARKER_:
|
189 |
+
obj = {}
|
190 |
+
if isinstance(obj, str):
|
191 |
+
obj = yaml.load(obj, Loader=get_yaml_loader())
|
192 |
+
if obj is None:
|
193 |
+
return OmegaConf.create({})
|
194 |
+
elif isinstance(obj, str):
|
195 |
+
return OmegaConf.create({obj: None})
|
196 |
+
else:
|
197 |
+
assert isinstance(obj, (list, dict))
|
198 |
+
return OmegaConf.create(obj)
|
199 |
+
|
200 |
+
else:
|
201 |
+
if (
|
202 |
+
is_primitive_dict(obj)
|
203 |
+
or OmegaConf.is_dict(obj)
|
204 |
+
or is_structured_config(obj)
|
205 |
+
or obj is None
|
206 |
+
):
|
207 |
+
ref_type = None
|
208 |
+
if is_structured_config(obj):
|
209 |
+
ref_type = get_type_of(obj)
|
210 |
+
elif OmegaConf.is_dict(obj):
|
211 |
+
ref_type = obj._metadata.ref_type
|
212 |
+
|
213 |
+
if ref_type is None:
|
214 |
+
ref_type = OmegaConf.get_type(obj)
|
215 |
+
|
216 |
+
if isinstance(obj, DictConfig):
|
217 |
+
key_type = obj._metadata.key_type
|
218 |
+
element_type = obj._metadata.element_type
|
219 |
+
else:
|
220 |
+
key_type, element_type = get_dict_key_value_types(ref_type)
|
221 |
+
return DictConfig(
|
222 |
+
content=obj,
|
223 |
+
parent=parent,
|
224 |
+
ref_type=ref_type,
|
225 |
+
key_type=key_type,
|
226 |
+
element_type=element_type,
|
227 |
+
)
|
228 |
+
elif is_primitive_list(obj) or OmegaConf.is_list(obj):
|
229 |
+
ref_type = OmegaConf.get_type(obj)
|
230 |
+
element_type = get_list_element_type(ref_type)
|
231 |
+
return ListConfig(
|
232 |
+
element_type=element_type, content=obj, parent=parent
|
233 |
+
)
|
234 |
+
else:
|
235 |
+
if isinstance(obj, type):
|
236 |
+
raise ValidationError(
|
237 |
+
f"Input class '{obj.__name__}' is not a structured config. "
|
238 |
+
"did you forget to decorate it as a dataclass?"
|
239 |
+
)
|
240 |
+
else:
|
241 |
+
raise ValidationError(
|
242 |
+
f"Object of unsupported type: '{type(obj).__name__}'"
|
243 |
+
)
|
244 |
+
except OmegaConfBaseException as e:
|
245 |
+
format_and_raise(node=None, key=None, value=None, msg=str(e), cause=e)
|
246 |
+
assert False
|
247 |
+
|
248 |
+
@staticmethod
|
249 |
+
def load(file_: Union[str, pathlib.Path, IO[Any]]) -> Union[DictConfig, ListConfig]:
|
250 |
+
from ._utils import get_yaml_loader
|
251 |
+
|
252 |
+
if isinstance(file_, (str, pathlib.Path)):
|
253 |
+
with io.open(os.path.abspath(file_), "r", encoding="utf-8") as f:
|
254 |
+
obj = yaml.load(f, Loader=get_yaml_loader())
|
255 |
+
if obj is None:
|
256 |
+
res = OmegaConf.create()
|
257 |
+
else:
|
258 |
+
res = OmegaConf.create(obj)
|
259 |
+
assert isinstance(res, (ListConfig, DictConfig))
|
260 |
+
return res
|
261 |
+
elif getattr(file_, "read", None):
|
262 |
+
obj = yaml.load(file_, Loader=get_yaml_loader())
|
263 |
+
assert isinstance(
|
264 |
+
obj, (list, dict, str)
|
265 |
+
), f"Invalid loaded object type : {type(obj).__name__}"
|
266 |
+
return OmegaConf.create(obj)
|
267 |
+
else:
|
268 |
+
raise TypeError("Unexpected file type")
|
269 |
+
|
270 |
+
@staticmethod
|
271 |
+
def save(
|
272 |
+
config: Any, f: Union[str, pathlib.Path, IO[Any]], resolve: bool = False
|
273 |
+
) -> None:
|
274 |
+
"""
|
275 |
+
Save as configuration object to a file
|
276 |
+
:param config: omegaconf.Config object (DictConfig or ListConfig).
|
277 |
+
:param f: filename or file object
|
278 |
+
:param resolve: True to save a resolved config (defaults to False)
|
279 |
+
"""
|
280 |
+
if is_dataclass(config) or is_attr_class(config):
|
281 |
+
config = OmegaConf.create(config)
|
282 |
+
data = OmegaConf.to_yaml(config, resolve=resolve)
|
283 |
+
if isinstance(f, (str, pathlib.Path)):
|
284 |
+
with io.open(os.path.abspath(f), "w", encoding="utf-8") as file:
|
285 |
+
file.write(data)
|
286 |
+
elif hasattr(f, "write"):
|
287 |
+
f.write(data)
|
288 |
+
f.flush()
|
289 |
+
else:
|
290 |
+
raise TypeError("Unexpected file type")
|
291 |
+
|
292 |
+
@staticmethod
|
293 |
+
def from_cli(args_list: Optional[List[str]] = None) -> DictConfig:
|
294 |
+
if args_list is None:
|
295 |
+
# Skip program name
|
296 |
+
args_list = sys.argv[1:]
|
297 |
+
return OmegaConf.from_dotlist(args_list)
|
298 |
+
|
299 |
+
@staticmethod
|
300 |
+
def from_dotlist(dotlist: List[str]) -> DictConfig:
|
301 |
+
"""
|
302 |
+
Creates config from the content sys.argv or from the specified args list of not None
|
303 |
+
:param dotlist:
|
304 |
+
:return:
|
305 |
+
"""
|
306 |
+
conf = OmegaConf.create()
|
307 |
+
conf.merge_with_dotlist(dotlist)
|
308 |
+
return conf
|
309 |
+
|
310 |
+
@staticmethod
|
311 |
+
def merge(
|
312 |
+
*others: Union[BaseContainer, Dict[str, Any], List[Any], Tuple[Any, ...], Any]
|
313 |
+
) -> Union[ListConfig, DictConfig]:
|
314 |
+
"""Merge a list of previously created configs into a single one"""
|
315 |
+
assert len(others) > 0
|
316 |
+
target = copy.deepcopy(others[0])
|
317 |
+
target = _ensure_container(target)
|
318 |
+
assert isinstance(target, (DictConfig, ListConfig))
|
319 |
+
|
320 |
+
with flag_override(target, "readonly", False):
|
321 |
+
target.merge_with(*others[1:])
|
322 |
+
turned_readonly = target._get_flag("readonly") is True
|
323 |
+
|
324 |
+
if turned_readonly:
|
325 |
+
OmegaConf.set_readonly(target, True)
|
326 |
+
|
327 |
+
return target
|
328 |
+
|
329 |
+
@staticmethod
|
330 |
+
def _tokenize_args(string: Optional[str]) -> List[str]:
|
331 |
+
if string is None or string == "":
|
332 |
+
return []
|
333 |
+
|
334 |
+
def _unescape_word_boundary(match: Match[str]) -> str:
|
335 |
+
if match.start() == 0 or match.end() == len(match.string):
|
336 |
+
return ""
|
337 |
+
return match.group(0)
|
338 |
+
|
339 |
+
escaped = re.split(r"(?<!\\),", string)
|
340 |
+
escaped = [re.sub(r"(?<!\\) ", _unescape_word_boundary, x) for x in escaped]
|
341 |
+
return [re.sub(r"(\\([ ,]))", lambda x: x.group(2), x) for x in escaped]
|
342 |
+
|
343 |
+
@staticmethod
|
344 |
+
def register_resolver(name: str, resolver: Resolver) -> None:
|
345 |
+
assert callable(resolver), "resolver must be callable"
|
346 |
+
# noinspection PyProtectedMember
|
347 |
+
assert (
|
348 |
+
name not in BaseContainer._resolvers
|
349 |
+
), "resolved {} is already registered".format(name)
|
350 |
+
|
351 |
+
def caching(config: BaseContainer, key: str) -> Any:
|
352 |
+
cache = OmegaConf.get_cache(config)[name]
|
353 |
+
val = (
|
354 |
+
cache[key] if key in cache else resolver(*OmegaConf._tokenize_args(key))
|
355 |
+
)
|
356 |
+
cache[key] = val
|
357 |
+
return val
|
358 |
+
|
359 |
+
# noinspection PyProtectedMember
|
360 |
+
BaseContainer._resolvers[name] = caching
|
361 |
+
|
362 |
+
@staticmethod
|
363 |
+
def get_resolver(name: str) -> Optional[Callable[[Container, Any], Any]]:
|
364 |
+
# noinspection PyProtectedMember
|
365 |
+
return (
|
366 |
+
BaseContainer._resolvers[name] if name in BaseContainer._resolvers else None
|
367 |
+
)
|
368 |
+
|
369 |
+
# noinspection PyProtectedMember
|
370 |
+
@staticmethod
|
371 |
+
def clear_resolvers() -> None:
|
372 |
+
BaseContainer._resolvers = {}
|
373 |
+
register_default_resolvers()
|
374 |
+
|
375 |
+
@staticmethod
|
376 |
+
def get_cache(conf: BaseContainer) -> Dict[str, Any]:
|
377 |
+
return conf._metadata.resolver_cache
|
378 |
+
|
379 |
+
@staticmethod
|
380 |
+
def set_cache(conf: BaseContainer, cache: Dict[str, Any]) -> None:
|
381 |
+
conf._metadata.resolver_cache = copy.deepcopy(cache)
|
382 |
+
|
383 |
+
@staticmethod
|
384 |
+
def clear_cache(conf: BaseContainer) -> None:
|
385 |
+
OmegaConf.set_cache(conf, defaultdict(dict, {}))
|
386 |
+
|
387 |
+
@staticmethod
|
388 |
+
def copy_cache(from_config: BaseContainer, to_config: BaseContainer) -> None:
|
389 |
+
OmegaConf.set_cache(to_config, OmegaConf.get_cache(from_config))
|
390 |
+
|
391 |
+
@staticmethod
|
392 |
+
def set_readonly(conf: Node, value: Optional[bool]) -> None:
|
393 |
+
# noinspection PyProtectedMember
|
394 |
+
conf._set_flag("readonly", value)
|
395 |
+
|
396 |
+
@staticmethod
|
397 |
+
def is_readonly(conf: Node) -> Optional[bool]:
|
398 |
+
# noinspection PyProtectedMember
|
399 |
+
return conf._get_flag("readonly")
|
400 |
+
|
401 |
+
@staticmethod
|
402 |
+
def set_struct(conf: Container, value: Optional[bool]) -> None:
|
403 |
+
# noinspection PyProtectedMember
|
404 |
+
conf._set_flag("struct", value)
|
405 |
+
|
406 |
+
@staticmethod
|
407 |
+
def is_struct(conf: Container) -> Optional[bool]:
|
408 |
+
# noinspection PyProtectedMember
|
409 |
+
return conf._get_flag("struct")
|
410 |
+
|
411 |
+
@staticmethod
|
412 |
+
def masked_copy(conf: DictConfig, keys: Union[str, List[str]]) -> DictConfig:
|
413 |
+
"""
|
414 |
+
Create a masked copy of of this config that contains a subset of the keys
|
415 |
+
:param conf: DictConfig object
|
416 |
+
:param keys: keys to preserve in the copy
|
417 |
+
:return:
|
418 |
+
"""
|
419 |
+
from .dictconfig import DictConfig
|
420 |
+
|
421 |
+
if not isinstance(conf, DictConfig):
|
422 |
+
raise ValueError("masked_copy is only supported for DictConfig")
|
423 |
+
|
424 |
+
if isinstance(keys, str):
|
425 |
+
keys = [keys]
|
426 |
+
content = {key: value for key, value in conf.items_ex(resolve=False, keys=keys)}
|
427 |
+
return DictConfig(content=content)
|
428 |
+
|
429 |
+
@staticmethod
|
430 |
+
def to_container(
|
431 |
+
cfg: Any, resolve: bool = False, enum_to_str: bool = False
|
432 |
+
) -> Union[Dict[str, Any], List[Any], None, str]:
|
433 |
+
"""
|
434 |
+
Resursively converts an OmegaConf config to a primitive container (dict or list).
|
435 |
+
:param cfg: the config to convert
|
436 |
+
:param resolve: True to resolve all values
|
437 |
+
:param enum_to_str: True to convert Enum values to strings
|
438 |
+
:return: A dict or a list representing this config as a primitive container.
|
439 |
+
"""
|
440 |
+
assert isinstance(cfg, Container)
|
441 |
+
# noinspection PyProtectedMember
|
442 |
+
return BaseContainer._to_content(cfg, resolve=resolve, enum_to_str=enum_to_str)
|
443 |
+
|
444 |
+
@staticmethod
|
445 |
+
def is_missing(cfg: Any, key: Union[int, str]) -> bool:
|
446 |
+
assert isinstance(cfg, Container)
|
447 |
+
try:
|
448 |
+
node = cfg._get_node(key)
|
449 |
+
if node is None:
|
450 |
+
return False
|
451 |
+
return node._is_missing()
|
452 |
+
except (UnsupportedInterpolationType, KeyError, AttributeError):
|
453 |
+
return False
|
454 |
+
|
455 |
+
@staticmethod
|
456 |
+
def is_optional(obj: Any, key: Optional[Union[int, str]] = None) -> bool:
|
457 |
+
if key is not None:
|
458 |
+
assert isinstance(obj, Container)
|
459 |
+
obj = obj._get_node(key)
|
460 |
+
if isinstance(obj, Node):
|
461 |
+
return obj._is_optional()
|
462 |
+
else:
|
463 |
+
return True
|
464 |
+
|
465 |
+
@staticmethod
|
466 |
+
def is_none(obj: Any, key: Optional[Union[int, str]] = None) -> bool:
|
467 |
+
if key is not None:
|
468 |
+
assert isinstance(obj, Container)
|
469 |
+
obj = obj._get_node(key)
|
470 |
+
if isinstance(obj, Node):
|
471 |
+
return obj._is_none()
|
472 |
+
else:
|
473 |
+
return obj is None
|
474 |
+
|
475 |
+
@staticmethod
|
476 |
+
def is_interpolation(node: Any, key: Optional[Union[int, str]] = None) -> bool:
|
477 |
+
if key is not None:
|
478 |
+
assert isinstance(node, Container)
|
479 |
+
target = node._get_node(key)
|
480 |
+
else:
|
481 |
+
target = node
|
482 |
+
if target is not None:
|
483 |
+
assert isinstance(target, Node)
|
484 |
+
return target._is_interpolation()
|
485 |
+
return False
|
486 |
+
|
487 |
+
@staticmethod
|
488 |
+
def is_list(obj: Any) -> bool:
|
489 |
+
from . import ListConfig
|
490 |
+
|
491 |
+
return isinstance(obj, ListConfig)
|
492 |
+
|
493 |
+
@staticmethod
|
494 |
+
def is_dict(obj: Any) -> bool:
|
495 |
+
from . import DictConfig
|
496 |
+
|
497 |
+
return isinstance(obj, DictConfig)
|
498 |
+
|
499 |
+
@staticmethod
|
500 |
+
def is_config(obj: Any) -> bool:
|
501 |
+
from . import Container
|
502 |
+
|
503 |
+
return isinstance(obj, Container)
|
504 |
+
|
505 |
+
@staticmethod
|
506 |
+
def get_type(obj: Any, key: Optional[str] = None) -> Optional[Type[Any]]:
|
507 |
+
if key is not None:
|
508 |
+
c = obj._get_node(key)
|
509 |
+
else:
|
510 |
+
c = obj
|
511 |
+
return OmegaConf._get_obj_type(c)
|
512 |
+
|
513 |
+
@staticmethod
|
514 |
+
def _get_obj_type(c: Any) -> Optional[Type[Any]]:
|
515 |
+
if is_structured_config(c):
|
516 |
+
return get_type_of(c)
|
517 |
+
elif c is None:
|
518 |
+
return None
|
519 |
+
elif isinstance(c, DictConfig):
|
520 |
+
if c._is_none():
|
521 |
+
return None
|
522 |
+
elif c._is_missing():
|
523 |
+
return None
|
524 |
+
else:
|
525 |
+
if is_structured_config(c._metadata.object_type):
|
526 |
+
return c._metadata.object_type
|
527 |
+
else:
|
528 |
+
return dict
|
529 |
+
elif isinstance(c, ListConfig):
|
530 |
+
return list
|
531 |
+
elif isinstance(c, ValueNode):
|
532 |
+
return type(c._value())
|
533 |
+
elif isinstance(c, dict):
|
534 |
+
return dict
|
535 |
+
elif isinstance(c, (list, tuple)):
|
536 |
+
return list
|
537 |
+
else:
|
538 |
+
return get_type_of(c)
|
539 |
+
|
540 |
+
@staticmethod
|
541 |
+
def select(cfg: Container, key: str, throw_on_missing: bool = False) -> Any:
|
542 |
+
try:
|
543 |
+
_root, _last_key, value = cfg._select_impl(
|
544 |
+
key, throw_on_missing=throw_on_missing, throw_on_resolution_failure=True
|
545 |
+
)
|
546 |
+
if value is not None and value._is_missing():
|
547 |
+
# throw_on_missing must be False
|
548 |
+
return None
|
549 |
+
|
550 |
+
return _get_value(value)
|
551 |
+
except Exception as e:
|
552 |
+
format_and_raise(node=cfg, key=key, value=None, cause=e, msg=str(e))
|
553 |
+
|
554 |
+
@staticmethod
|
555 |
+
def update(
|
556 |
+
cfg: Container, key: str, value: Any = None, merge: Optional[bool] = None
|
557 |
+
) -> None:
|
558 |
+
"""
|
559 |
+
Updates a dot separated key sequence to a value
|
560 |
+
|
561 |
+
:param cfg: input config to update
|
562 |
+
:param key: key to update (can be a dot separated path)
|
563 |
+
:param value: value to set, if value if a list or a dict it will be merged or set
|
564 |
+
depending on merge_config_values
|
565 |
+
:param merge: If value is a dict or a list, True for merge, False for set.
|
566 |
+
True to merge
|
567 |
+
False to set
|
568 |
+
None (default) : deprecation warning and default to False
|
569 |
+
"""
|
570 |
+
|
571 |
+
if merge is None:
|
572 |
+
warnings.warn(
|
573 |
+
dedent(
|
574 |
+
"""\
|
575 |
+
update() merge flag is is not specified, defaulting to False.
|
576 |
+
For more details, see https://github.com/omry/omegaconf/issues/367"""
|
577 |
+
),
|
578 |
+
category=UserWarning,
|
579 |
+
stacklevel=1,
|
580 |
+
)
|
581 |
+
merge = False
|
582 |
+
|
583 |
+
split = key.split(".")
|
584 |
+
root = cfg
|
585 |
+
for i in range(len(split) - 1):
|
586 |
+
k = split[i]
|
587 |
+
# if next_root is a primitive (string, int etc) replace it with an empty map
|
588 |
+
next_root, key_ = _select_one(root, k, throw_on_missing=False)
|
589 |
+
if not isinstance(next_root, Container):
|
590 |
+
root[key_] = {}
|
591 |
+
root = root[key_]
|
592 |
+
|
593 |
+
last = split[-1]
|
594 |
+
|
595 |
+
assert isinstance(
|
596 |
+
root, Container
|
597 |
+
), f"Unexpected type for root : {type(root).__name__}"
|
598 |
+
|
599 |
+
last_key: Union[str, int] = last
|
600 |
+
if isinstance(root, ListConfig):
|
601 |
+
last_key = int(last)
|
602 |
+
|
603 |
+
if merge and (OmegaConf.is_config(value) or is_primitive_container(value)):
|
604 |
+
assert isinstance(root, BaseContainer)
|
605 |
+
node = root._get_node(last_key)
|
606 |
+
if OmegaConf.is_config(node):
|
607 |
+
assert isinstance(node, BaseContainer)
|
608 |
+
node.merge_with(value)
|
609 |
+
return
|
610 |
+
|
611 |
+
if OmegaConf.is_dict(root):
|
612 |
+
assert isinstance(last_key, str)
|
613 |
+
root.__setattr__(last_key, value)
|
614 |
+
elif OmegaConf.is_list(root):
|
615 |
+
assert isinstance(last_key, int)
|
616 |
+
root.__setitem__(last_key, value)
|
617 |
+
else:
|
618 |
+
assert False
|
619 |
+
|
620 |
+
@staticmethod
|
621 |
+
def to_yaml(cfg: Any, *, resolve: bool = False, sort_keys: bool = False) -> str:
|
622 |
+
"""
|
623 |
+
returns a yaml dump of this config object.
|
624 |
+
:param cfg: Config object, Structured Config type or instance
|
625 |
+
:param resolve: if True, will return a string with the interpolations resolved, otherwise
|
626 |
+
interpolations are preserved
|
627 |
+
:param sort_keys: If True, will print dict keys in sorted order. default False.
|
628 |
+
:return: A string containing the yaml representation.
|
629 |
+
"""
|
630 |
+
cfg = _ensure_container(cfg)
|
631 |
+
container = OmegaConf.to_container(cfg, resolve=resolve, enum_to_str=True)
|
632 |
+
return yaml.dump( # type: ignore
|
633 |
+
container,
|
634 |
+
default_flow_style=False,
|
635 |
+
allow_unicode=True,
|
636 |
+
sort_keys=sort_keys,
|
637 |
+
Dumper=get_omega_conf_dumper(),
|
638 |
+
)
|
639 |
+
|
640 |
+
|
641 |
+
# register all default resolvers
|
642 |
+
register_default_resolvers()
|
643 |
+
|
644 |
+
|
645 |
+
@contextmanager
|
646 |
+
def flag_override(
|
647 |
+
config: Node, name: str, value: Optional[bool]
|
648 |
+
) -> Generator[Node, None, None]:
|
649 |
+
prev_state = config._get_flag(name)
|
650 |
+
try:
|
651 |
+
config._set_flag(name, value)
|
652 |
+
yield config
|
653 |
+
finally:
|
654 |
+
config._set_flag(name, prev_state)
|
655 |
+
|
656 |
+
|
657 |
+
@contextmanager
|
658 |
+
def read_write(config: Node) -> Generator[Node, None, None]:
|
659 |
+
prev_state = config._get_node_flag("readonly")
|
660 |
+
try:
|
661 |
+
OmegaConf.set_readonly(config, False)
|
662 |
+
yield config
|
663 |
+
finally:
|
664 |
+
OmegaConf.set_readonly(config, prev_state)
|
665 |
+
|
666 |
+
|
667 |
+
@contextmanager
|
668 |
+
def open_dict(config: Container) -> Generator[Container, None, None]:
|
669 |
+
prev_state = config._get_node_flag("struct")
|
670 |
+
try:
|
671 |
+
OmegaConf.set_struct(config, False)
|
672 |
+
yield config
|
673 |
+
finally:
|
674 |
+
OmegaConf.set_struct(config, prev_state)
|
675 |
+
|
676 |
+
|
677 |
+
# === private === #
|
678 |
+
|
679 |
+
|
680 |
+
def _node_wrap(
|
681 |
+
type_: Any,
|
682 |
+
parent: Optional[BaseContainer],
|
683 |
+
is_optional: bool,
|
684 |
+
value: Any,
|
685 |
+
key: Any,
|
686 |
+
ref_type: Any = None,
|
687 |
+
) -> Node:
|
688 |
+
node: Node
|
689 |
+
is_dict = type(value) is dict or is_dict_annotation(type_)
|
690 |
+
is_list = (
|
691 |
+
type(value) in (list, tuple)
|
692 |
+
or is_list_annotation(type_)
|
693 |
+
or is_tuple_annotation(type_)
|
694 |
+
)
|
695 |
+
if is_dict:
|
696 |
+
key_type, element_type = get_dict_key_value_types(type_)
|
697 |
+
node = DictConfig(
|
698 |
+
content=value,
|
699 |
+
key=key,
|
700 |
+
parent=parent,
|
701 |
+
ref_type=type_,
|
702 |
+
is_optional=is_optional,
|
703 |
+
key_type=key_type,
|
704 |
+
element_type=element_type,
|
705 |
+
)
|
706 |
+
elif is_list:
|
707 |
+
element_type = get_list_element_type(type_)
|
708 |
+
node = ListConfig(
|
709 |
+
content=value,
|
710 |
+
key=key,
|
711 |
+
parent=parent,
|
712 |
+
is_optional=is_optional,
|
713 |
+
element_type=element_type,
|
714 |
+
ref_type=ref_type,
|
715 |
+
)
|
716 |
+
elif is_structured_config(type_) or is_structured_config(value):
|
717 |
+
key_type, element_type = get_dict_key_value_types(type_)
|
718 |
+
node = DictConfig(
|
719 |
+
ref_type=type_,
|
720 |
+
is_optional=is_optional,
|
721 |
+
content=value,
|
722 |
+
key=key,
|
723 |
+
parent=parent,
|
724 |
+
key_type=key_type,
|
725 |
+
element_type=element_type,
|
726 |
+
)
|
727 |
+
elif type_ == Any or type_ is None:
|
728 |
+
node = AnyNode(value=value, key=key, parent=parent, is_optional=is_optional)
|
729 |
+
elif issubclass(type_, Enum):
|
730 |
+
node = EnumNode(
|
731 |
+
enum_type=type_,
|
732 |
+
value=value,
|
733 |
+
key=key,
|
734 |
+
parent=parent,
|
735 |
+
is_optional=is_optional,
|
736 |
+
)
|
737 |
+
elif type_ == int:
|
738 |
+
node = IntegerNode(value=value, key=key, parent=parent, is_optional=is_optional)
|
739 |
+
elif type_ == float:
|
740 |
+
node = FloatNode(value=value, key=key, parent=parent, is_optional=is_optional)
|
741 |
+
elif type_ == bool:
|
742 |
+
node = BooleanNode(value=value, key=key, parent=parent, is_optional=is_optional)
|
743 |
+
elif type_ == str:
|
744 |
+
node = StringNode(value=value, key=key, parent=parent, is_optional=is_optional)
|
745 |
+
else:
|
746 |
+
raise ValidationError(f"Unexpected object type : {type_str(type_)}")
|
747 |
+
return node
|
748 |
+
|
749 |
+
|
750 |
+
def _maybe_wrap(
|
751 |
+
ref_type: Any,
|
752 |
+
key: Any,
|
753 |
+
value: Any,
|
754 |
+
is_optional: bool,
|
755 |
+
parent: Optional[BaseContainer],
|
756 |
+
) -> Node:
|
757 |
+
# if already a node, update key and parent and return as is.
|
758 |
+
# NOTE: that this mutate the input node!
|
759 |
+
if isinstance(value, Node):
|
760 |
+
value._set_key(key)
|
761 |
+
value._set_parent(parent)
|
762 |
+
return value
|
763 |
+
else:
|
764 |
+
return _node_wrap(
|
765 |
+
type_=ref_type,
|
766 |
+
parent=parent,
|
767 |
+
is_optional=is_optional,
|
768 |
+
value=value,
|
769 |
+
key=key,
|
770 |
+
ref_type=ref_type,
|
771 |
+
)
|
772 |
+
|
773 |
+
|
774 |
+
def _select_one(
|
775 |
+
c: Container, key: str, throw_on_missing: bool, throw_on_type_error: bool = True
|
776 |
+
) -> Tuple[Optional[Node], Union[str, int]]:
|
777 |
+
from .dictconfig import DictConfig
|
778 |
+
from .listconfig import ListConfig
|
779 |
+
|
780 |
+
ret_key: Union[str, int] = key
|
781 |
+
assert isinstance(c, (DictConfig, ListConfig)), f"Unexpected type : {c}"
|
782 |
+
if isinstance(c, DictConfig):
|
783 |
+
assert isinstance(ret_key, str)
|
784 |
+
val: Optional[Node] = c._get_node(ret_key, validate_access=False)
|
785 |
+
if val is not None:
|
786 |
+
if val._is_missing():
|
787 |
+
if throw_on_missing:
|
788 |
+
raise MissingMandatoryValue(
|
789 |
+
f"Missing mandatory value : {c._get_full_key(ret_key)}"
|
790 |
+
)
|
791 |
+
else:
|
792 |
+
return val, ret_key
|
793 |
+
else:
|
794 |
+
val = None
|
795 |
+
elif isinstance(c, ListConfig):
|
796 |
+
assert isinstance(ret_key, str)
|
797 |
+
if not is_int(ret_key):
|
798 |
+
if throw_on_type_error:
|
799 |
+
raise TypeError(
|
800 |
+
f"Index '{ret_key}' ({type(ret_key).__name__}) is not an int"
|
801 |
+
)
|
802 |
+
else:
|
803 |
+
val = None
|
804 |
+
else:
|
805 |
+
ret_key = int(ret_key)
|
806 |
+
if ret_key < 0 or ret_key + 1 > len(c):
|
807 |
+
val = None
|
808 |
+
else:
|
809 |
+
val = c._get_node(ret_key)
|
810 |
+
else:
|
811 |
+
assert False
|
812 |
+
|
813 |
+
return val, ret_key
|
omegaconf/py.typed
ADDED
File without changes
|
omegaconf/version.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys # pragma: no cover
|
2 |
+
|
3 |
+
__version__ = "2.0.6"
|
4 |
+
|
5 |
+
msg = """OmegaConf 2.0 and above is compatible with Python 3.6 and newer.
|
6 |
+
You have the following options:
|
7 |
+
1. Upgrade to Python 3.6 or newer.
|
8 |
+
This is highly recommended. new features will not be added to OmegaConf 1.4.
|
9 |
+
2. Continue using OmegaConf 1.4:
|
10 |
+
You can pip install 'OmegaConf<1.5' to do that.
|
11 |
+
"""
|
12 |
+
if sys.version_info < (3, 6):
|
13 |
+
raise ImportError(msg) # pragma: no cover
|
pyproject.toml
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[tool.towncrier]
|
2 |
+
package = "omegaconf"
|
3 |
+
package_dir = ""
|
4 |
+
filename = "NEWS.md"
|
5 |
+
directory = "news/"
|
6 |
+
title_format = "## {version} ({project_date})"
|
7 |
+
template = "news/_template.rst"
|
8 |
+
issue_format = "[#{issue}](https://github.com/omry/omegaconf/issues/{issue})"
|
9 |
+
start_string = "<!-- TOWNCRIER -->\n"
|
10 |
+
underlines = [""]
|
11 |
+
|
12 |
+
[[tool.towncrier.type]]
|
13 |
+
directory = "feature"
|
14 |
+
name = "Features"
|
15 |
+
showcontent = true
|
16 |
+
|
17 |
+
[[tool.towncrier.type]]
|
18 |
+
directory = "bugfix"
|
19 |
+
name = "Bug Fixes"
|
20 |
+
showcontent = true
|
21 |
+
|
22 |
+
[[tool.towncrier.type]]
|
23 |
+
directory = "removal"
|
24 |
+
name = "Deprecations and Removals"
|
25 |
+
showcontent = true
|
26 |
+
|
27 |
+
[[tool.towncrier.type]]
|
28 |
+
directory = "docs"
|
29 |
+
name = "Improved Documentation"
|
30 |
+
showcontent = true
|
31 |
+
|
32 |
+
[[tool.towncrier.type]]
|
33 |
+
directory = "misc"
|
34 |
+
name = "Miscellaneous changes"
|
35 |
+
showcontent = true
|
requirements/base.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
PyYAML>=5.1.*
|
2 |
+
# Use dataclasses backport for Python 3.6.
|
3 |
+
dataclasses;python_version=='3.6'
|
4 |
+
typing-extensions
|
setup.cfg
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[aliases]
|
2 |
+
test = pytest
|
3 |
+
|
4 |
+
[mypy]
|
5 |
+
python_version = 3.6
|
6 |
+
mypy_path = .stubs
|
7 |
+
|
8 |
+
[egg_info]
|
9 |
+
tag_build =
|
10 |
+
tag_date = 0
|
11 |
+
|
setup.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# type: ignore
|
2 |
+
"""
|
3 |
+
OmegaConf setup
|
4 |
+
Instructions:
|
5 |
+
# Build:
|
6 |
+
rm -rf dist/ omegaconf.egg-info/
|
7 |
+
python setup.py sdist bdist_wheel
|
8 |
+
# Upload:
|
9 |
+
twine upload dist/*
|
10 |
+
"""
|
11 |
+
import codecs
|
12 |
+
import os
|
13 |
+
import pathlib
|
14 |
+
import re
|
15 |
+
|
16 |
+
import pkg_resources
|
17 |
+
import setuptools
|
18 |
+
|
19 |
+
with pathlib.Path("requirements/base.txt").open() as requirements_txt:
|
20 |
+
install_requires = [
|
21 |
+
str(requirement)
|
22 |
+
for requirement in pkg_resources.parse_requirements(requirements_txt)
|
23 |
+
]
|
24 |
+
|
25 |
+
|
26 |
+
def find_version(*file_paths):
|
27 |
+
here = os.path.abspath(os.path.dirname(__file__))
|
28 |
+
|
29 |
+
def read(*parts):
|
30 |
+
with codecs.open(os.path.join(here, *parts), "r") as fp:
|
31 |
+
return fp.read()
|
32 |
+
|
33 |
+
version_file = read(*file_paths)
|
34 |
+
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
|
35 |
+
if version_match:
|
36 |
+
return version_match.group(1)
|
37 |
+
raise RuntimeError("Unable to find version string.")
|
38 |
+
|
39 |
+
|
40 |
+
with open("README.md", "r") as fh:
|
41 |
+
LONG_DESC = fh.read()
|
42 |
+
setuptools.setup(
|
43 |
+
name="omegaconf",
|
44 |
+
version=find_version("omegaconf", "version.py"),
|
45 |
+
author="Omry Yadan",
|
46 |
+
author_email="[email protected]",
|
47 |
+
description="A flexible configuration library",
|
48 |
+
long_description=LONG_DESC,
|
49 |
+
long_description_content_type="text/markdown",
|
50 |
+
setup_requires=["pytest-runner"],
|
51 |
+
tests_require=["pytest"],
|
52 |
+
url="https://github.com/omry/omegaconf",
|
53 |
+
keywords="yaml configuration config",
|
54 |
+
packages=["omegaconf"],
|
55 |
+
python_requires=">=3.6",
|
56 |
+
classifiers=[
|
57 |
+
"Programming Language :: Python :: 3.6",
|
58 |
+
"Programming Language :: Python :: 3.7",
|
59 |
+
"Programming Language :: Python :: 3.8",
|
60 |
+
"License :: OSI Approved :: BSD License",
|
61 |
+
"Operating System :: OS Independent",
|
62 |
+
],
|
63 |
+
install_requires=install_requires,
|
64 |
+
package_data={"omegaconf": ["py.typed"]},
|
65 |
+
)
|
tests/__init__.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from contextlib import contextmanager
|
2 |
+
from dataclasses import dataclass, field
|
3 |
+
from enum import Enum
|
4 |
+
from typing import Any, Dict, Iterator, List, Optional, Union
|
5 |
+
|
6 |
+
import attr
|
7 |
+
|
8 |
+
from omegaconf import II, MISSING
|
9 |
+
|
10 |
+
|
11 |
+
class IllegalType:
|
12 |
+
def __init__(self) -> None:
|
13 |
+
pass
|
14 |
+
|
15 |
+
def __eq__(self, other: Any) -> bool:
|
16 |
+
if isinstance(other, IllegalType):
|
17 |
+
return True
|
18 |
+
return False
|
19 |
+
|
20 |
+
|
21 |
+
@contextmanager
|
22 |
+
def does_not_raise(enter_result: Any = None) -> Iterator[Any]:
|
23 |
+
yield enter_result
|
24 |
+
|
25 |
+
|
26 |
+
class Color(Enum):
|
27 |
+
RED = 1
|
28 |
+
GREEN = 2
|
29 |
+
BLUE = 3
|
30 |
+
|
31 |
+
|
32 |
+
@dataclass
|
33 |
+
class User:
|
34 |
+
name: str = MISSING
|
35 |
+
age: int = MISSING
|
36 |
+
|
37 |
+
|
38 |
+
@dataclass
|
39 |
+
class Group:
|
40 |
+
admin: Optional[User] = None
|
41 |
+
|
42 |
+
|
43 |
+
class Enum1(Enum):
|
44 |
+
FOO = 1
|
45 |
+
BAR = 2
|
46 |
+
|
47 |
+
|
48 |
+
@dataclass
|
49 |
+
class Users:
|
50 |
+
name2user: Dict[str, User] = field(default_factory=dict)
|
51 |
+
|
52 |
+
|
53 |
+
@dataclass
|
54 |
+
class ConfWithMissingDict:
|
55 |
+
dict: Dict[str, Any] = MISSING
|
56 |
+
|
57 |
+
|
58 |
+
@dataclass
|
59 |
+
class Plugin:
|
60 |
+
name: str = MISSING
|
61 |
+
params: Any = MISSING
|
62 |
+
|
63 |
+
|
64 |
+
@dataclass
|
65 |
+
class ConcretePlugin(Plugin):
|
66 |
+
name: str = "foobar_plugin"
|
67 |
+
|
68 |
+
@dataclass
|
69 |
+
class FoobarParams:
|
70 |
+
foo: int = 10
|
71 |
+
|
72 |
+
params: FoobarParams = FoobarParams()
|
73 |
+
|
74 |
+
|
75 |
+
@dataclass
|
76 |
+
class StructuredWithMissing:
|
77 |
+
num: int = MISSING
|
78 |
+
opt_num: Optional[int] = MISSING
|
79 |
+
dict: Dict[str, str] = MISSING
|
80 |
+
opt_dict: Optional[Dict[str, str]] = MISSING
|
81 |
+
list: List[str] = MISSING
|
82 |
+
opt_list: Optional[List[str]] = MISSING
|
83 |
+
user: User = MISSING
|
84 |
+
opt_user: Optional[User] = MISSING
|
85 |
+
inter_num: int = II("num")
|
86 |
+
inter_user: User = II("user")
|
87 |
+
inter_opt_user: Optional[User] = II("opt_user")
|
88 |
+
|
89 |
+
|
90 |
+
@dataclass
|
91 |
+
class UnionError:
|
92 |
+
x: Union[int, str] = 10
|
93 |
+
|
94 |
+
|
95 |
+
@dataclass
|
96 |
+
class MissingList:
|
97 |
+
list: List[str] = MISSING
|
98 |
+
|
99 |
+
|
100 |
+
@dataclass
|
101 |
+
class MissingDict:
|
102 |
+
dict: Dict[str, str] = MISSING
|
103 |
+
|
104 |
+
|
105 |
+
@dataclass
|
106 |
+
class DictEnum:
|
107 |
+
color_key: Dict[Color, str] = field(default_factory=lambda: {})
|
108 |
+
color_val: Dict[str, Color] = field(default_factory=lambda: {})
|
109 |
+
|
110 |
+
|
111 |
+
@dataclass
|
112 |
+
class A:
|
113 |
+
a: int = 10
|
114 |
+
|
115 |
+
|
116 |
+
@dataclass
|
117 |
+
class B:
|
118 |
+
x: A = MISSING
|
119 |
+
|
120 |
+
|
121 |
+
@dataclass
|
122 |
+
class C:
|
123 |
+
x: Optional[A] = None
|
124 |
+
|
125 |
+
|
126 |
+
@dataclass
|
127 |
+
class PersonD:
|
128 |
+
age: int = 18
|
129 |
+
registered: bool = True
|
130 |
+
|
131 |
+
|
132 |
+
@attr.s(auto_attribs=True)
|
133 |
+
class PersonA:
|
134 |
+
age: int = 18
|
135 |
+
registered: bool = True
|
136 |
+
|
137 |
+
|
138 |
+
@dataclass
|
139 |
+
class Module:
|
140 |
+
name: str = MISSING
|
141 |
+
classes: List[str] = MISSING
|
142 |
+
|
143 |
+
|
144 |
+
@dataclass
|
145 |
+
class Package:
|
146 |
+
modules: List[Module] = MISSING
|
147 |
+
|
148 |
+
|
149 |
+
@dataclass
|
150 |
+
class InterpolationList:
|
151 |
+
list: List[float] = II("optimization.lr")
|
152 |
+
|
153 |
+
|
154 |
+
@dataclass
|
155 |
+
class InterpolationDict:
|
156 |
+
dict: Dict[str, int] = II("optimization.lr")
|
tests/conftest.py
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
from typing import Any
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from omegaconf.basecontainer import BaseContainer
|
7 |
+
|
8 |
+
|
9 |
+
@pytest.fixture(scope="function") # type: ignore
|
10 |
+
def restore_resolvers() -> Any:
|
11 |
+
"""
|
12 |
+
A fixture to restore singletons state after this the function.
|
13 |
+
This is useful for functions that are making a one-off change to singlestons that should not effect
|
14 |
+
other tests
|
15 |
+
"""
|
16 |
+
state = copy.deepcopy(BaseContainer._resolvers)
|
17 |
+
yield
|
18 |
+
BaseContainer._resolvers = state
|
tests/examples/__init__.py
ADDED
File without changes
|
tests/examples/test_dataclass_example.py
ADDED
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass, field
|
2 |
+
from enum import Enum
|
3 |
+
from typing import Any, Dict, List, Optional
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from omegaconf import (
|
8 |
+
MISSING,
|
9 |
+
DictConfig,
|
10 |
+
MissingMandatoryValue,
|
11 |
+
OmegaConf,
|
12 |
+
ReadonlyConfigError,
|
13 |
+
ValidationError,
|
14 |
+
)
|
15 |
+
|
16 |
+
|
17 |
+
class Height(Enum):
|
18 |
+
SHORT = 0
|
19 |
+
TALL = 1
|
20 |
+
|
21 |
+
|
22 |
+
@dataclass
|
23 |
+
class SimpleTypes:
|
24 |
+
num: int = 10
|
25 |
+
pi: float = 3.1415
|
26 |
+
is_awesome: bool = True
|
27 |
+
height: Height = Height.SHORT
|
28 |
+
description: str = "text"
|
29 |
+
|
30 |
+
|
31 |
+
def test_simple_types_class() -> None:
|
32 |
+
# Instantiate from a class
|
33 |
+
conf = OmegaConf.structured(SimpleTypes)
|
34 |
+
assert conf.num == 10
|
35 |
+
assert conf.pi == 3.1415
|
36 |
+
assert conf.is_awesome is True
|
37 |
+
assert conf.height == Height.SHORT
|
38 |
+
assert conf.description == "text"
|
39 |
+
|
40 |
+
|
41 |
+
def test_static_typing() -> None:
|
42 |
+
conf: SimpleTypes = OmegaConf.structured(SimpleTypes)
|
43 |
+
assert conf.description == "text" # passes static type checking
|
44 |
+
with pytest.raises(AttributeError):
|
45 |
+
# This will fail both the static type checking and at runtime
|
46 |
+
# noinspection PyStatementEffect
|
47 |
+
conf.no_such_attribute # type: ignore
|
48 |
+
|
49 |
+
|
50 |
+
def test_simple_types_obj() -> None:
|
51 |
+
# Instantiate from an Object, any value can be overridden
|
52 |
+
# at construction
|
53 |
+
conf = OmegaConf.structured(SimpleTypes(num=20, pi=3))
|
54 |
+
assert conf.num == 20
|
55 |
+
assert conf.pi == 3
|
56 |
+
# Everything not overridden at construction takes the default value
|
57 |
+
assert conf.is_awesome is True
|
58 |
+
assert conf.height == Height.SHORT
|
59 |
+
assert conf.description == "text"
|
60 |
+
|
61 |
+
|
62 |
+
def test_conversions() -> None:
|
63 |
+
conf: SimpleTypes = OmegaConf.structured(SimpleTypes)
|
64 |
+
|
65 |
+
# OmegaConf can convert types at runtime
|
66 |
+
conf.num = 20 # ok, type matches
|
67 |
+
|
68 |
+
# ok, the String "20" is converted to the int 20
|
69 |
+
conf.num = "20" # type: ignore
|
70 |
+
|
71 |
+
assert conf.num == 20
|
72 |
+
with pytest.raises(ValidationError):
|
73 |
+
# ValidationError: "one" cannot be converted to an integer
|
74 |
+
conf.num = "one" # type: ignore
|
75 |
+
|
76 |
+
# booleans can take many forms
|
77 |
+
for expected, values in {
|
78 |
+
True: ["on", "yes", "true", True, "1"],
|
79 |
+
False: ["off", "no", "false", False, "0"],
|
80 |
+
}.items():
|
81 |
+
for b in values:
|
82 |
+
conf.is_awesome = b # type: ignore
|
83 |
+
assert conf.is_awesome == expected
|
84 |
+
|
85 |
+
# Enums too
|
86 |
+
for expected1, values1 in {
|
87 |
+
Height.SHORT: [Height.SHORT, "Height.SHORT", "SHORT", 0],
|
88 |
+
Height.TALL: [Height.TALL, "Height.TALL", "TALL", 1],
|
89 |
+
}.items():
|
90 |
+
for b in values1:
|
91 |
+
conf.height = b # type: ignore
|
92 |
+
assert conf.height == expected1
|
93 |
+
|
94 |
+
|
95 |
+
@dataclass
|
96 |
+
class Modifiers:
|
97 |
+
# regular field
|
98 |
+
num: int = 10
|
99 |
+
|
100 |
+
# Fields can be optional
|
101 |
+
optional_num: Optional[int] = None
|
102 |
+
|
103 |
+
# MISSING fields must be populated at runtime before access. accessing them while they
|
104 |
+
# are missing will result in a MissingMandatoryValue exception
|
105 |
+
another_num: int = MISSING
|
106 |
+
|
107 |
+
|
108 |
+
def test_modifiers() -> None:
|
109 |
+
conf: Modifiers = OmegaConf.structured(Modifiers)
|
110 |
+
# regular fields cannot take None
|
111 |
+
with pytest.raises(ValidationError):
|
112 |
+
conf.num = None # type: ignore
|
113 |
+
|
114 |
+
# but Optional fields can
|
115 |
+
conf.optional_num = None
|
116 |
+
assert conf.optional_num is None
|
117 |
+
|
118 |
+
# Accessing a missing field will trigger MissingMandatoryValue exception
|
119 |
+
with pytest.raises(MissingMandatoryValue):
|
120 |
+
# noinspection PyStatementEffect
|
121 |
+
conf.another_num
|
122 |
+
|
123 |
+
# but you can access it once it's been assigned
|
124 |
+
conf.another_num = 42
|
125 |
+
assert conf.another_num == 42
|
126 |
+
|
127 |
+
|
128 |
+
@dataclass
|
129 |
+
class User:
|
130 |
+
# A simple user class with two missing fields
|
131 |
+
name: str = MISSING
|
132 |
+
height: Height = MISSING
|
133 |
+
|
134 |
+
|
135 |
+
# Group class contains two instances of User.
|
136 |
+
@dataclass
|
137 |
+
class Group:
|
138 |
+
name: str = MISSING
|
139 |
+
# data classes can be nested
|
140 |
+
admin: User = User # type: ignore
|
141 |
+
|
142 |
+
# You can also specify different defaults for nested classes
|
143 |
+
manager: User = User(name="manager", height=Height.TALL)
|
144 |
+
|
145 |
+
|
146 |
+
def test_nesting() -> None:
|
147 |
+
conf = OmegaConf.structured(Group)
|
148 |
+
assert conf == {
|
149 |
+
"name": "???",
|
150 |
+
"admin": {"name": MISSING, "height": MISSING},
|
151 |
+
"manager": {"name": "manager", "height": Height.TALL},
|
152 |
+
}
|
153 |
+
|
154 |
+
expected = """name: ???
|
155 |
+
admin:
|
156 |
+
name: ???
|
157 |
+
height: ???
|
158 |
+
manager:
|
159 |
+
name: manager
|
160 |
+
height: TALL
|
161 |
+
"""
|
162 |
+
assert OmegaConf.to_yaml(conf) == expected
|
163 |
+
|
164 |
+
# you can assign a different object of the same type
|
165 |
+
conf.admin = User(name="omry", height=Height.TALL)
|
166 |
+
with pytest.raises(ValidationError):
|
167 |
+
# but not incompatible types
|
168 |
+
conf.admin = 10
|
169 |
+
|
170 |
+
with pytest.raises(ValidationError):
|
171 |
+
# You can't assign a dict even if the field matches
|
172 |
+
conf.manager = {"name": "secret", "height": Height.TALL}
|
173 |
+
|
174 |
+
|
175 |
+
@dataclass
|
176 |
+
class Lists:
|
177 |
+
# List with Any as type can take any primitive type OmegaConf supports:
|
178 |
+
# int, float, bool, str and Enums as well as Any (which is the same as not having a specified type).
|
179 |
+
untyped_list: List[Any] = field(default_factory=lambda: [1, "foo", True])
|
180 |
+
|
181 |
+
# typed lists can hold int, bool, str, float or enums.
|
182 |
+
int_list: List[int] = field(default_factory=lambda: [10, 20, 30])
|
183 |
+
|
184 |
+
|
185 |
+
def test_typed_list_runtime_validation() -> None:
|
186 |
+
conf = OmegaConf.structured(Lists)
|
187 |
+
|
188 |
+
conf.untyped_list[0] = True # okay, list can hold any primitive type
|
189 |
+
|
190 |
+
conf.int_list[0] = 999 # okay
|
191 |
+
assert conf.int_list[0] == 999
|
192 |
+
|
193 |
+
conf.int_list[0] = "1000" # also ok!
|
194 |
+
assert conf.int_list[0] == 1000
|
195 |
+
|
196 |
+
with pytest.raises(ValidationError):
|
197 |
+
conf.int_list[0] = "fail"
|
198 |
+
|
199 |
+
|
200 |
+
# Dicts
|
201 |
+
@dataclass
|
202 |
+
class Dicts:
|
203 |
+
# Key must be a string or Enum, value can be any primitive type OmegaConf supports:
|
204 |
+
# int, float, bool, str and Enums as well as Any (which is the same as not having a specified type).
|
205 |
+
untyped_dict: Dict[str, Any] = field(
|
206 |
+
default_factory=lambda: {"foo": True, "bar": 100}
|
207 |
+
)
|
208 |
+
|
209 |
+
# maps string to height Enum
|
210 |
+
str_to_height: Dict[str, Height] = field(
|
211 |
+
default_factory=lambda: {"Yoda": Height.SHORT, "3-CPO": Height.TALL}
|
212 |
+
)
|
213 |
+
|
214 |
+
|
215 |
+
def test_typed_dict_runtime_validation() -> None:
|
216 |
+
conf = OmegaConf.structured(Dicts)
|
217 |
+
conf.untyped_dict["foo"] = "buzz" # okay, list can hold any primitive type
|
218 |
+
conf.str_to_height["Shorty"] = Height.SHORT # Okay
|
219 |
+
with pytest.raises(ValidationError):
|
220 |
+
# runtime failure, cannot convert True to Height
|
221 |
+
conf.str_to_height["Yoda"] = True
|
222 |
+
|
223 |
+
|
224 |
+
# Frozen
|
225 |
+
@dataclass(frozen=True)
|
226 |
+
class FrozenClass:
|
227 |
+
x: int = 10
|
228 |
+
list: List[int] = field(default_factory=lambda: [1, 2, 3])
|
229 |
+
|
230 |
+
|
231 |
+
def test_frozen() -> None:
|
232 |
+
# frozen classes are read only, attempts to modify them at runtime
|
233 |
+
# will result in a ReadonlyConfigError
|
234 |
+
conf = OmegaConf.structured(FrozenClass)
|
235 |
+
with pytest.raises(ReadonlyConfigError):
|
236 |
+
conf.x = 20
|
237 |
+
|
238 |
+
# Read-only flag is recursive
|
239 |
+
with pytest.raises(ReadonlyConfigError):
|
240 |
+
conf.list[0] = 20
|
241 |
+
|
242 |
+
|
243 |
+
class Protocol(Enum):
|
244 |
+
HTTP = 0
|
245 |
+
HTTPS = 1
|
246 |
+
|
247 |
+
|
248 |
+
@dataclass
|
249 |
+
class Domain:
|
250 |
+
name: str = MISSING
|
251 |
+
path: str = MISSING
|
252 |
+
protocols: List[Protocol] = field(default_factory=lambda: [Protocol.HTTPS])
|
253 |
+
|
254 |
+
|
255 |
+
@dataclass
|
256 |
+
class WebServer(DictConfig):
|
257 |
+
protocol_ports: Dict[Protocol, int] = field(
|
258 |
+
default_factory=lambda: {Protocol.HTTP: 80, Protocol.HTTPS: 443}
|
259 |
+
)
|
260 |
+
# Dict of name to domain
|
261 |
+
domains: Dict[str, Domain] = field(default_factory=dict)
|
262 |
+
|
263 |
+
# List of all domains
|
264 |
+
domains_list: List[Domain] = field(default_factory=list)
|
265 |
+
|
266 |
+
|
267 |
+
# Test that Enum can be used a dictionary key
|
268 |
+
def test_enum_key() -> None:
|
269 |
+
conf = OmegaConf.structured(WebServer)
|
270 |
+
# When an Enum is a dictionary key the name of the Enum is actually used
|
271 |
+
# as the key
|
272 |
+
assert conf.protocol_ports.HTTP == 80
|
273 |
+
assert conf.protocol_ports["HTTP"] == 80
|
274 |
+
assert conf.protocol_ports[Protocol.HTTP] == 80
|
275 |
+
|
276 |
+
|
277 |
+
def test_dict_of_objects() -> None:
|
278 |
+
conf: WebServer = OmegaConf.structured(WebServer)
|
279 |
+
conf.domains["blog"] = Domain(name="blog.example.com", path="/www/blog.example.com")
|
280 |
+
with pytest.raises(ValidationError):
|
281 |
+
conf.domains.foo = 10 # type: ignore
|
282 |
+
|
283 |
+
assert conf.domains["blog"].name == "blog.example.com"
|
284 |
+
assert conf.domains["blog"].path == "/www/blog.example.com"
|
285 |
+
assert conf == {
|
286 |
+
"protocol_ports": {Protocol.HTTP: 80, Protocol.HTTPS: 443},
|
287 |
+
"domains": {
|
288 |
+
"blog": {
|
289 |
+
"name": "blog.example.com",
|
290 |
+
"path": "/www/blog.example.com",
|
291 |
+
"protocols": [Protocol.HTTPS],
|
292 |
+
}
|
293 |
+
},
|
294 |
+
"domains_list": [],
|
295 |
+
}
|
296 |
+
|
297 |
+
|
298 |
+
def test_list_of_objects() -> None:
|
299 |
+
conf: WebServer = OmegaConf.structured(WebServer)
|
300 |
+
conf.domains_list.append(
|
301 |
+
Domain(name="blog.example.com", path="/www/blog.example.com")
|
302 |
+
)
|
303 |
+
with pytest.raises(ValidationError):
|
304 |
+
conf.domains_list.append(10) # type: ignore
|
305 |
+
|
306 |
+
assert conf.domains_list[0].name == "blog.example.com"
|
307 |
+
assert conf.domains_list[0].path == "/www/blog.example.com"
|
308 |
+
assert conf == {
|
309 |
+
"protocol_ports": {Protocol.HTTP: 80, Protocol.HTTPS: 443},
|
310 |
+
"domains": {},
|
311 |
+
"domains_list": [
|
312 |
+
{
|
313 |
+
"name": "blog.example.com",
|
314 |
+
"path": "/www/blog.example.com",
|
315 |
+
"protocols": [Protocol.HTTPS],
|
316 |
+
}
|
317 |
+
],
|
318 |
+
}
|
319 |
+
|
320 |
+
|
321 |
+
def test_merge() -> None:
|
322 |
+
@dataclass
|
323 |
+
class Config:
|
324 |
+
num: int = 10
|
325 |
+
user: User = User(name=MISSING, height=MISSING)
|
326 |
+
domains: Dict[str, Domain] = field(default_factory=dict)
|
327 |
+
|
328 |
+
yaml = """
|
329 |
+
user:
|
330 |
+
name: Omry
|
331 |
+
domains:
|
332 |
+
blog_website:
|
333 |
+
name: blog
|
334 |
+
protocols:
|
335 |
+
- HTTPS
|
336 |
+
"""
|
337 |
+
|
338 |
+
schema: Config = OmegaConf.structured(Config)
|
339 |
+
cfg = OmegaConf.create(yaml)
|
340 |
+
merged: Any = OmegaConf.merge(schema, cfg)
|
341 |
+
assert merged == {
|
342 |
+
"num": 10,
|
343 |
+
"user": {"name": "Omry", "height": "???"},
|
344 |
+
"domains": {
|
345 |
+
"blog_website": {
|
346 |
+
"name": "blog",
|
347 |
+
"path": "???",
|
348 |
+
"protocols": [Protocol.HTTPS],
|
349 |
+
}
|
350 |
+
},
|
351 |
+
}
|
352 |
+
assert OmegaConf.is_missing(merged.domains.blog_website, "path")
|
353 |
+
|
354 |
+
|
355 |
+
def test_merge_example() -> None:
|
356 |
+
@dataclass
|
357 |
+
class Server:
|
358 |
+
port: int = MISSING
|
359 |
+
|
360 |
+
@dataclass
|
361 |
+
class Log:
|
362 |
+
file: str = MISSING
|
363 |
+
rotation: int = MISSING
|
364 |
+
|
365 |
+
@dataclass
|
366 |
+
class MyConfig:
|
367 |
+
server: Server = Server()
|
368 |
+
log: Log = Log()
|
369 |
+
users: List[str] = field(default_factory=list)
|
370 |
+
numbers: List[int] = field(default_factory=list)
|
371 |
+
|
372 |
+
schema = OmegaConf.structured(MyConfig)
|
373 |
+
with pytest.raises(ValidationError):
|
374 |
+
OmegaConf.merge(schema, OmegaConf.create({"log": {"rotation": "foo"}}))
|
375 |
+
|
376 |
+
with pytest.raises(ValidationError):
|
377 |
+
cfg = schema.copy()
|
378 |
+
cfg.numbers.append("fo")
|
379 |
+
|
380 |
+
with pytest.raises(ValidationError):
|
381 |
+
OmegaConf.merge(schema, OmegaConf.create({"numbers": ["foo"]}))
|
tests/structured_conf/__init__.py
ADDED
File without changes
|
tests/structured_conf/data/__init__.py
ADDED
File without changes
|
tests/structured_conf/data/attr_classes.py
ADDED
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
2 |
+
|
3 |
+
import attr
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from omegaconf import II, MISSING, SI
|
7 |
+
from tests import Color
|
8 |
+
|
9 |
+
# attr is a dependency of pytest which means it's always available when testing with pytest.
|
10 |
+
pytest.importorskip("attr")
|
11 |
+
|
12 |
+
|
13 |
+
class NotStructuredConfig:
|
14 |
+
name: str = "Bond"
|
15 |
+
age: int = 7
|
16 |
+
|
17 |
+
|
18 |
+
@attr.s(auto_attribs=True)
|
19 |
+
class StructuredWithInvalidField:
|
20 |
+
bar: NotStructuredConfig = NotStructuredConfig()
|
21 |
+
|
22 |
+
|
23 |
+
@attr.s(auto_attribs=True)
|
24 |
+
class User:
|
25 |
+
name: str = MISSING
|
26 |
+
age: int = MISSING
|
27 |
+
|
28 |
+
|
29 |
+
@attr.s(auto_attribs=True)
|
30 |
+
class UserList:
|
31 |
+
list: List[User] = MISSING
|
32 |
+
|
33 |
+
|
34 |
+
@attr.s(auto_attribs=True)
|
35 |
+
class UserDict:
|
36 |
+
dict: Dict[str, User] = MISSING
|
37 |
+
|
38 |
+
|
39 |
+
@attr.s(auto_attribs=True)
|
40 |
+
class AnyTypeConfig:
|
41 |
+
with_default: Any = "Can get any type at runtime"
|
42 |
+
null_default: Any = None
|
43 |
+
# Access to this prior to assigning a value to it will result in
|
44 |
+
# a MissingMandatoryValue exception.
|
45 |
+
# Equivalent to "???" in YAML files
|
46 |
+
mandatory_missing: Any = MISSING
|
47 |
+
|
48 |
+
# interpolation, will inherit the type and value of `with_default'
|
49 |
+
interpolation: Any = II("with_default")
|
50 |
+
|
51 |
+
# specific types assigned
|
52 |
+
int_default: Any = 12
|
53 |
+
float_default: Any = 10.0
|
54 |
+
str_default: Any = "foobar"
|
55 |
+
bool_default: Any = True
|
56 |
+
enum_default: Any = Color.BLUE
|
57 |
+
|
58 |
+
# test mixing with variable with a specific type annotation
|
59 |
+
typed_int_default: int = 10
|
60 |
+
|
61 |
+
|
62 |
+
@attr.s(auto_attribs=True)
|
63 |
+
class BoolConfig:
|
64 |
+
|
65 |
+
# with default value
|
66 |
+
with_default: bool = True
|
67 |
+
|
68 |
+
# default is None
|
69 |
+
null_default: Optional[bool] = None
|
70 |
+
|
71 |
+
# explicit no default
|
72 |
+
mandatory_missing: bool = MISSING
|
73 |
+
|
74 |
+
# interpolation, will inherit the type and value of `with_default'
|
75 |
+
interpolation: bool = II("with_default")
|
76 |
+
|
77 |
+
|
78 |
+
@attr.s(auto_attribs=True)
|
79 |
+
class IntegersConfig:
|
80 |
+
|
81 |
+
# with default value
|
82 |
+
with_default: int = 10
|
83 |
+
|
84 |
+
# default is None
|
85 |
+
null_default: Optional[int] = None
|
86 |
+
|
87 |
+
# explicit no default
|
88 |
+
mandatory_missing: int = MISSING
|
89 |
+
|
90 |
+
# interpolation, will inherit the type and value of `with_default'
|
91 |
+
interpolation: int = II("with_default")
|
92 |
+
|
93 |
+
|
94 |
+
@attr.s(auto_attribs=True)
|
95 |
+
class StringConfig:
|
96 |
+
|
97 |
+
# with default value
|
98 |
+
with_default: str = "foo"
|
99 |
+
|
100 |
+
# default is None
|
101 |
+
null_default: Optional[str] = None
|
102 |
+
|
103 |
+
# explicit no default
|
104 |
+
mandatory_missing: str = MISSING
|
105 |
+
|
106 |
+
# interpolation, will inherit the type and value of `with_default'
|
107 |
+
interpolation: str = II("with_default")
|
108 |
+
|
109 |
+
|
110 |
+
@attr.s(auto_attribs=True)
|
111 |
+
class FloatConfig:
|
112 |
+
|
113 |
+
# with default value
|
114 |
+
with_default: float = 0.10
|
115 |
+
|
116 |
+
# default is None
|
117 |
+
null_default: Optional[float] = None
|
118 |
+
|
119 |
+
# explicit no default
|
120 |
+
mandatory_missing: float = MISSING
|
121 |
+
|
122 |
+
# interpolation, will inherit the type and value of `with_default'
|
123 |
+
interpolation: float = II("with_default")
|
124 |
+
|
125 |
+
|
126 |
+
@attr.s(auto_attribs=True)
|
127 |
+
class EnumConfig:
|
128 |
+
|
129 |
+
# with default value
|
130 |
+
with_default: Color = Color.BLUE
|
131 |
+
|
132 |
+
# default is None
|
133 |
+
null_default: Optional[Color] = None
|
134 |
+
|
135 |
+
# explicit no default
|
136 |
+
mandatory_missing: Color = MISSING
|
137 |
+
|
138 |
+
# interpolation, will inherit the type and value of `with_default'
|
139 |
+
interpolation: Color = II("with_default")
|
140 |
+
|
141 |
+
|
142 |
+
@attr.s(auto_attribs=True)
|
143 |
+
class ConfigWithList:
|
144 |
+
list1: List[int] = [1, 2, 3]
|
145 |
+
list2: Tuple[int, int, int] = (1, 2, 3)
|
146 |
+
missing: List[int] = MISSING
|
147 |
+
|
148 |
+
|
149 |
+
@attr.s(auto_attribs=True)
|
150 |
+
class ConfigWithDict:
|
151 |
+
dict1: Dict[str, Any] = {"foo": "bar"}
|
152 |
+
missing: Dict[str, Any] = MISSING
|
153 |
+
|
154 |
+
|
155 |
+
@attr.s(auto_attribs=True)
|
156 |
+
class ConfigWithDict2:
|
157 |
+
dict1: Dict[str, int] = {"foo": 2}
|
158 |
+
|
159 |
+
|
160 |
+
@attr.s(auto_attribs=True)
|
161 |
+
class Nested:
|
162 |
+
# with default value
|
163 |
+
with_default: int = 10
|
164 |
+
|
165 |
+
# default is None
|
166 |
+
null_default: Optional[int] = None
|
167 |
+
|
168 |
+
# explicit no default
|
169 |
+
mandatory_missing: int = MISSING
|
170 |
+
|
171 |
+
# Note that since relative interpolations are not yet supported,
|
172 |
+
# Nested configs and interpolations does not play too well together
|
173 |
+
interpolation: int = II("value_at_root")
|
174 |
+
|
175 |
+
|
176 |
+
@attr.s(auto_attribs=True)
|
177 |
+
class NestedSubclass(Nested):
|
178 |
+
additional: int = 20
|
179 |
+
|
180 |
+
|
181 |
+
@attr.s(auto_attribs=True)
|
182 |
+
class NestedConfig:
|
183 |
+
default_value: Nested
|
184 |
+
|
185 |
+
# with default value
|
186 |
+
user_provided_default: Nested = Nested(with_default=42)
|
187 |
+
|
188 |
+
value_at_root: int = 1000
|
189 |
+
|
190 |
+
|
191 |
+
@attr.s(auto_attribs=True)
|
192 |
+
class NestedWithAny:
|
193 |
+
var: Any = Nested()
|
194 |
+
|
195 |
+
|
196 |
+
@attr.s(auto_attribs=True)
|
197 |
+
class NoDefaultErrors:
|
198 |
+
no_default: Any
|
199 |
+
|
200 |
+
|
201 |
+
@attr.s(auto_attribs=True)
|
202 |
+
class Interpolation:
|
203 |
+
x: int = 100
|
204 |
+
y: int = 200
|
205 |
+
# The real type of y is int, cast the interpolation string
|
206 |
+
# to help static type checkers to see this truth
|
207 |
+
z1: int = II("x")
|
208 |
+
z2: str = SI("${x}_${y}")
|
209 |
+
|
210 |
+
|
211 |
+
@attr.s(auto_attribs=True)
|
212 |
+
class BoolOptional:
|
213 |
+
with_default: Optional[bool] = True
|
214 |
+
as_none: Optional[bool] = None
|
215 |
+
not_optional: bool = True
|
216 |
+
|
217 |
+
|
218 |
+
@attr.s(auto_attribs=True)
|
219 |
+
class IntegerOptional:
|
220 |
+
with_default: Optional[int] = 1
|
221 |
+
as_none: Optional[int] = None
|
222 |
+
not_optional: int = 1
|
223 |
+
|
224 |
+
|
225 |
+
@attr.s(auto_attribs=True)
|
226 |
+
class FloatOptional:
|
227 |
+
with_default: Optional[float] = 1.0
|
228 |
+
as_none: Optional[float] = None
|
229 |
+
not_optional: float = 1
|
230 |
+
|
231 |
+
|
232 |
+
@attr.s(auto_attribs=True)
|
233 |
+
class StringOptional:
|
234 |
+
with_default: Optional[str] = "foo"
|
235 |
+
as_none: Optional[str] = None
|
236 |
+
not_optional: str = "foo"
|
237 |
+
|
238 |
+
|
239 |
+
@attr.s(auto_attribs=True)
|
240 |
+
class ListOptional:
|
241 |
+
with_default: Optional[List[int]] = [1, 2, 3]
|
242 |
+
as_none: Optional[List[int]] = None
|
243 |
+
not_optional: List[int] = [1, 2, 3]
|
244 |
+
|
245 |
+
|
246 |
+
@attr.s(auto_attribs=True)
|
247 |
+
class TupleOptional:
|
248 |
+
with_default: Optional[Tuple[int, int, int]] = (1, 2, 3)
|
249 |
+
as_none: Optional[Tuple[int, int, int]] = None
|
250 |
+
not_optional: Tuple[int, int, int] = (1, 2, 3)
|
251 |
+
|
252 |
+
|
253 |
+
@attr.s(auto_attribs=True)
|
254 |
+
class EnumOptional:
|
255 |
+
with_default: Optional[Color] = Color.BLUE
|
256 |
+
as_none: Optional[Color] = None
|
257 |
+
not_optional: Color = Color.BLUE
|
258 |
+
|
259 |
+
|
260 |
+
@attr.s(auto_attribs=True)
|
261 |
+
class DictOptional:
|
262 |
+
with_default: Optional[Dict[str, int]] = {"a": 10}
|
263 |
+
as_none: Optional[Dict[str, int]] = None
|
264 |
+
not_optional: Dict[str, int] = {"a": 10}
|
265 |
+
|
266 |
+
|
267 |
+
@attr.s(auto_attribs=True)
|
268 |
+
class StructuredOptional:
|
269 |
+
with_default: Optional[Nested] = Nested()
|
270 |
+
as_none: Optional[Nested] = None
|
271 |
+
not_optional: Nested = Nested()
|
272 |
+
|
273 |
+
|
274 |
+
@attr.s(auto_attribs=True, frozen=True)
|
275 |
+
class FrozenClass:
|
276 |
+
user: User = User(name="Bart", age=10)
|
277 |
+
x: int = 10
|
278 |
+
list: List[int] = [1, 2, 3]
|
279 |
+
|
280 |
+
|
281 |
+
@attr.s(auto_attribs=True)
|
282 |
+
class ContainsFrozen:
|
283 |
+
x: int = 10
|
284 |
+
frozen: FrozenClass = FrozenClass()
|
285 |
+
|
286 |
+
|
287 |
+
@attr.s(auto_attribs=True)
|
288 |
+
class WithTypedList:
|
289 |
+
list: List[int] = [1, 2, 3]
|
290 |
+
|
291 |
+
|
292 |
+
@attr.s(auto_attribs=True)
|
293 |
+
class WithTypedDict:
|
294 |
+
dict: Dict[str, int] = {"foo": 10, "bar": 20}
|
295 |
+
|
296 |
+
|
297 |
+
@attr.s(auto_attribs=True)
|
298 |
+
class ErrorDictIntKey:
|
299 |
+
# invalid dict key, must be str
|
300 |
+
dict: Dict[int, str] = {10: "foo", 20: "bar"}
|
301 |
+
|
302 |
+
|
303 |
+
class RegularClass:
|
304 |
+
pass
|
305 |
+
|
306 |
+
|
307 |
+
@attr.s(auto_attribs=True)
|
308 |
+
class ErrorDictUnsupportedValue:
|
309 |
+
# invalid dict value type, not one of the supported types
|
310 |
+
dict: Dict[str, RegularClass] = {}
|
311 |
+
|
312 |
+
|
313 |
+
@attr.s(auto_attribs=True)
|
314 |
+
class ErrorListUnsupportedValue:
|
315 |
+
# invalid dict value type, not one of the supported types
|
316 |
+
dict: List[RegularClass] = []
|
317 |
+
|
318 |
+
|
319 |
+
@attr.s(auto_attribs=True)
|
320 |
+
class ListExamples:
|
321 |
+
any: List[Any] = [1, "foo"]
|
322 |
+
ints: List[int] = [1, 2]
|
323 |
+
strings: List[str] = ["foo", "bar"]
|
324 |
+
booleans: List[bool] = [True, False]
|
325 |
+
colors: List[Color] = [Color.RED, Color.GREEN]
|
326 |
+
|
327 |
+
|
328 |
+
@attr.s(auto_attribs=True)
|
329 |
+
class TupleExamples:
|
330 |
+
any: Tuple[Any, Any] = (1, "foo")
|
331 |
+
ints: Tuple[int, int] = (1, 2)
|
332 |
+
strings: Tuple[str, str] = ("foo", "bar")
|
333 |
+
booleans: Tuple[bool, bool] = (True, False)
|
334 |
+
colors: Tuple[Color, Color] = (Color.RED, Color.GREEN)
|
335 |
+
|
336 |
+
|
337 |
+
@attr.s(auto_attribs=True)
|
338 |
+
class DictExamples:
|
339 |
+
any: Dict[str, Any] = {"a": 1, "b": "foo"}
|
340 |
+
ints: Dict[str, int] = {"a": 10, "b": 20}
|
341 |
+
strings: Dict[str, str] = {"a": "foo", "b": "bar"}
|
342 |
+
booleans: Dict[str, bool] = {"a": True, "b": False}
|
343 |
+
colors: Dict[str, Color] = {
|
344 |
+
"red": Color.RED,
|
345 |
+
"green": Color.GREEN,
|
346 |
+
"blue": Color.BLUE,
|
347 |
+
}
|
348 |
+
|
349 |
+
|
350 |
+
@attr.s(auto_attribs=True)
|
351 |
+
class DictWithEnumKeys:
|
352 |
+
enum_key: Dict[Color, str] = {Color.RED: "red", Color.GREEN: "green"}
|
353 |
+
|
354 |
+
|
355 |
+
@attr.s(auto_attribs=True)
|
356 |
+
class DictOfObjects:
|
357 |
+
users: Dict[str, User] = {"joe": User(name="Joe", age=18)}
|
358 |
+
|
359 |
+
|
360 |
+
@attr.s(auto_attribs=True)
|
361 |
+
class ListOfObjects:
|
362 |
+
users: List[User] = [User(name="Joe", age=18)]
|
363 |
+
|
364 |
+
|
365 |
+
class DictSubclass:
|
366 |
+
@attr.s(auto_attribs=True)
|
367 |
+
class Str2Str(Dict[str, str]):
|
368 |
+
pass
|
369 |
+
|
370 |
+
@attr.s(auto_attribs=True)
|
371 |
+
class Color2Str(Dict[Color, str]):
|
372 |
+
pass
|
373 |
+
|
374 |
+
@attr.s(auto_attribs=True)
|
375 |
+
class Color2Color(Dict[Color, Color]):
|
376 |
+
pass
|
377 |
+
|
378 |
+
@attr.s(auto_attribs=True)
|
379 |
+
class Str2User(Dict[str, User]):
|
380 |
+
pass
|
381 |
+
|
382 |
+
@attr.s(auto_attribs=True)
|
383 |
+
class Str2StrWithField(Dict[str, str]):
|
384 |
+
foo: str = "bar"
|
385 |
+
|
386 |
+
@attr.s(auto_attribs=True)
|
387 |
+
class Str2IntWithStrField(Dict[str, int]):
|
388 |
+
foo: str = "bar"
|
389 |
+
|
390 |
+
class Error:
|
391 |
+
@attr.s(auto_attribs=True)
|
392 |
+
class User2Str(Dict[User, str]):
|
393 |
+
pass
|
394 |
+
|
395 |
+
|
396 |
+
@attr.s(auto_attribs=True)
|
397 |
+
class Plugin:
|
398 |
+
name: str = MISSING
|
399 |
+
params: Any = MISSING
|
400 |
+
|
401 |
+
|
402 |
+
@attr.s(auto_attribs=True)
|
403 |
+
class ConcretePlugin(Plugin):
|
404 |
+
name: str = "foobar_plugin"
|
405 |
+
|
406 |
+
@attr.s(auto_attribs=True)
|
407 |
+
class FoobarParams:
|
408 |
+
foo: int = 10
|
409 |
+
|
410 |
+
params: FoobarParams = FoobarParams()
|
411 |
+
|
412 |
+
|
413 |
+
@attr.s(auto_attribs=True)
|
414 |
+
class PluginWithAdditionalField(Plugin):
|
415 |
+
name: str = "foobar2_plugin"
|
416 |
+
additional: int = 10
|
417 |
+
|
418 |
+
|
419 |
+
# Does not extend Plugin, cannot be assigned or merged
|
420 |
+
@attr.s(auto_attribs=True)
|
421 |
+
class FaultyPlugin:
|
422 |
+
name: str = "faulty_plugin"
|
423 |
+
|
424 |
+
|
425 |
+
@attr.s(auto_attribs=True)
|
426 |
+
class PluginHolder:
|
427 |
+
none: Optional[Plugin] = None
|
428 |
+
missing: Plugin = MISSING
|
429 |
+
plugin: Plugin = Plugin()
|
430 |
+
plugin2: Plugin = ConcretePlugin()
|
431 |
+
|
432 |
+
|
433 |
+
@attr.s(auto_attribs=True)
|
434 |
+
class LinkedList:
|
435 |
+
next: Optional["LinkedList"] = None
|
436 |
+
value: Any = MISSING
|
437 |
+
|
438 |
+
|
439 |
+
class MissingTest:
|
440 |
+
@attr.s(auto_attribs=True)
|
441 |
+
class Missing1:
|
442 |
+
head: LinkedList = MISSING
|
443 |
+
|
444 |
+
@attr.s(auto_attribs=True)
|
445 |
+
class Missing2:
|
446 |
+
head: LinkedList = LinkedList(next=MISSING, value=1)
|
447 |
+
|
448 |
+
|
449 |
+
@attr.s(auto_attribs=True)
|
450 |
+
class NestedWithNone:
|
451 |
+
plugin: Optional[Plugin] = None
|
452 |
+
|
453 |
+
|
454 |
+
@attr.s(auto_attribs=True)
|
455 |
+
class UnionError:
|
456 |
+
x: Union[int, str] = 10
|
457 |
+
|
458 |
+
|
459 |
+
@attr.s(auto_attribs=True)
|
460 |
+
class WithNativeMISSING:
|
461 |
+
num: int = attr.NOTHING # type: ignore
|
462 |
+
|
463 |
+
|
464 |
+
@attr.s(auto_attribs=True)
|
465 |
+
class MissingStructuredConfigField:
|
466 |
+
plugin: Plugin = MISSING
|
467 |
+
|
468 |
+
|
469 |
+
@attr.s(auto_attribs=True)
|
470 |
+
class ListClass:
|
471 |
+
list: List[int] = []
|
472 |
+
tuple: Tuple[int, int] = (1, 2)
|
tests/structured_conf/data/dataclasses.py
ADDED
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from dataclasses import dataclass, field
|
3 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from omegaconf import II, MISSING, SI
|
8 |
+
from tests import Color
|
9 |
+
|
10 |
+
# skip test if dataclasses are not available
|
11 |
+
pytest.importorskip("dataclasses")
|
12 |
+
|
13 |
+
|
14 |
+
class NotStructuredConfig:
|
15 |
+
name: str = "Bond"
|
16 |
+
age: int = 7
|
17 |
+
|
18 |
+
|
19 |
+
@dataclass
|
20 |
+
class StructuredWithInvalidField:
|
21 |
+
bar: NotStructuredConfig = NotStructuredConfig()
|
22 |
+
|
23 |
+
|
24 |
+
@dataclass
|
25 |
+
class User:
|
26 |
+
name: str = MISSING
|
27 |
+
age: int = MISSING
|
28 |
+
|
29 |
+
|
30 |
+
@dataclass
|
31 |
+
class UserList:
|
32 |
+
list: List[User] = MISSING
|
33 |
+
|
34 |
+
|
35 |
+
@dataclass
|
36 |
+
class UserDict:
|
37 |
+
dict: Dict[str, User] = MISSING
|
38 |
+
|
39 |
+
|
40 |
+
@dataclass
|
41 |
+
class AnyTypeConfig:
|
42 |
+
with_default: Any = "Can get any type at runtime"
|
43 |
+
null_default: Any = None
|
44 |
+
# Access to this prior to assigning a value to it will result in
|
45 |
+
# a MissingMandatoryValue exception.
|
46 |
+
# Equivalent to "???" in YAML files
|
47 |
+
mandatory_missing: Any = MISSING
|
48 |
+
|
49 |
+
# interpolation, will inherit the type and value of `with_default'
|
50 |
+
interpolation: Any = II("with_default")
|
51 |
+
|
52 |
+
# specific types assigned
|
53 |
+
int_default: Any = 12
|
54 |
+
float_default: Any = 10.0
|
55 |
+
str_default: Any = "foobar"
|
56 |
+
bool_default: Any = True
|
57 |
+
enum_default: Any = Color.BLUE
|
58 |
+
|
59 |
+
# test mixing with variable with a specific type annotation
|
60 |
+
typed_int_default: int = 10
|
61 |
+
|
62 |
+
|
63 |
+
@dataclass
|
64 |
+
class BoolConfig:
|
65 |
+
# with default value
|
66 |
+
with_default: bool = True
|
67 |
+
|
68 |
+
# default is None
|
69 |
+
null_default: Optional[bool] = None
|
70 |
+
|
71 |
+
# explicit no default
|
72 |
+
mandatory_missing: bool = MISSING
|
73 |
+
|
74 |
+
# interpolation, will inherit the type and value of `with_default'
|
75 |
+
interpolation: bool = II("with_default")
|
76 |
+
|
77 |
+
|
78 |
+
@dataclass
|
79 |
+
class IntegersConfig:
|
80 |
+
# with default value
|
81 |
+
with_default: int = 10
|
82 |
+
|
83 |
+
# default is None
|
84 |
+
null_default: Optional[int] = None
|
85 |
+
|
86 |
+
# explicit no default
|
87 |
+
mandatory_missing: int = MISSING
|
88 |
+
|
89 |
+
# interpolation, will inherit the type and value of `with_default'
|
90 |
+
interpolation: int = II("with_default")
|
91 |
+
|
92 |
+
|
93 |
+
@dataclass
|
94 |
+
class StringConfig:
|
95 |
+
# with default value
|
96 |
+
with_default: str = "foo"
|
97 |
+
|
98 |
+
# default is None
|
99 |
+
null_default: Optional[str] = None
|
100 |
+
|
101 |
+
# explicit no default
|
102 |
+
mandatory_missing: str = MISSING
|
103 |
+
|
104 |
+
# interpolation, will inherit the type and value of `with_default'
|
105 |
+
interpolation: str = II("with_default")
|
106 |
+
|
107 |
+
|
108 |
+
@dataclass
|
109 |
+
class FloatConfig:
|
110 |
+
# with default value
|
111 |
+
with_default: float = 0.10
|
112 |
+
|
113 |
+
# default is None
|
114 |
+
null_default: Optional[float] = None
|
115 |
+
|
116 |
+
# explicit no default
|
117 |
+
mandatory_missing: float = MISSING
|
118 |
+
|
119 |
+
# interpolation, will inherit the type and value of `with_default'
|
120 |
+
interpolation: float = II("with_default")
|
121 |
+
|
122 |
+
|
123 |
+
@dataclass
|
124 |
+
class EnumConfig:
|
125 |
+
# with default value
|
126 |
+
with_default: Color = Color.BLUE
|
127 |
+
|
128 |
+
# default is None
|
129 |
+
null_default: Optional[Color] = None
|
130 |
+
|
131 |
+
# explicit no default
|
132 |
+
mandatory_missing: Color = MISSING
|
133 |
+
|
134 |
+
# interpolation, will inherit the type and value of `with_default'
|
135 |
+
interpolation: Color = II("with_default")
|
136 |
+
|
137 |
+
|
138 |
+
@dataclass
|
139 |
+
class ConfigWithList:
|
140 |
+
list1: List[int] = field(default_factory=lambda: [1, 2, 3])
|
141 |
+
list2: Tuple[int, int, int] = field(default_factory=lambda: (1, 2, 3))
|
142 |
+
missing: List[int] = MISSING
|
143 |
+
|
144 |
+
|
145 |
+
@dataclass
|
146 |
+
class ConfigWithDict:
|
147 |
+
dict1: Dict[str, Any] = field(default_factory=lambda: {"foo": "bar"})
|
148 |
+
missing: Dict[str, Any] = MISSING
|
149 |
+
|
150 |
+
|
151 |
+
@dataclass
|
152 |
+
class ConfigWithDict2:
|
153 |
+
dict1: Dict[str, int] = field(default_factory=lambda: {"foo": 2})
|
154 |
+
|
155 |
+
|
156 |
+
@dataclass
|
157 |
+
class Nested:
|
158 |
+
# with default value
|
159 |
+
with_default: int = 10
|
160 |
+
|
161 |
+
# default is None
|
162 |
+
null_default: Optional[int] = None
|
163 |
+
|
164 |
+
# explicit no default
|
165 |
+
mandatory_missing: int = MISSING
|
166 |
+
|
167 |
+
# Note that since relative interpolations are not yet supported,
|
168 |
+
# Nested configs and interpolations does not play too well together
|
169 |
+
interpolation: int = II("value_at_root")
|
170 |
+
|
171 |
+
|
172 |
+
@dataclass
|
173 |
+
class NestedSubclass(Nested):
|
174 |
+
additional: int = 20
|
175 |
+
|
176 |
+
|
177 |
+
@dataclass
|
178 |
+
class NestedConfig:
|
179 |
+
default_value: Nested
|
180 |
+
|
181 |
+
# with default value
|
182 |
+
user_provided_default: Nested = Nested(with_default=42)
|
183 |
+
|
184 |
+
value_at_root: int = 1000
|
185 |
+
|
186 |
+
|
187 |
+
@dataclass
|
188 |
+
class NestedWithAny:
|
189 |
+
var: Any = Nested()
|
190 |
+
|
191 |
+
|
192 |
+
@dataclass
|
193 |
+
class NoDefaultErrors:
|
194 |
+
no_default: Any
|
195 |
+
|
196 |
+
|
197 |
+
@dataclass
|
198 |
+
class Interpolation:
|
199 |
+
x: int = 100
|
200 |
+
y: int = 200
|
201 |
+
# The real type of y is int, cast the interpolation string
|
202 |
+
# to help static type checkers to see this truth
|
203 |
+
z1: int = II("x")
|
204 |
+
z2: str = SI("${x}_${y}")
|
205 |
+
|
206 |
+
|
207 |
+
@dataclass
|
208 |
+
class BoolOptional:
|
209 |
+
with_default: Optional[bool] = True
|
210 |
+
as_none: Optional[bool] = None
|
211 |
+
not_optional: bool = True
|
212 |
+
|
213 |
+
|
214 |
+
@dataclass
|
215 |
+
class IntegerOptional:
|
216 |
+
with_default: Optional[int] = 1
|
217 |
+
as_none: Optional[int] = None
|
218 |
+
not_optional: int = 1
|
219 |
+
|
220 |
+
|
221 |
+
@dataclass
|
222 |
+
class FloatOptional:
|
223 |
+
with_default: Optional[float] = 1.0
|
224 |
+
as_none: Optional[float] = None
|
225 |
+
not_optional: float = 1
|
226 |
+
|
227 |
+
|
228 |
+
@dataclass
|
229 |
+
class StringOptional:
|
230 |
+
with_default: Optional[str] = "foo"
|
231 |
+
as_none: Optional[str] = None
|
232 |
+
not_optional: str = "foo"
|
233 |
+
|
234 |
+
|
235 |
+
@dataclass
|
236 |
+
class ListOptional:
|
237 |
+
with_default: Optional[List[int]] = field(default_factory=lambda: [1, 2, 3])
|
238 |
+
as_none: Optional[List[int]] = None
|
239 |
+
not_optional: List[int] = field(default_factory=lambda: [1, 2, 3])
|
240 |
+
|
241 |
+
|
242 |
+
@dataclass
|
243 |
+
class TupleOptional:
|
244 |
+
with_default: Optional[Tuple[int, int, int]] = field(
|
245 |
+
default_factory=lambda: (1, 2, 3)
|
246 |
+
)
|
247 |
+
as_none: Optional[Tuple[int, int, int]] = None
|
248 |
+
not_optional: Tuple[int, int, int] = field(default_factory=lambda: (1, 2, 3))
|
249 |
+
|
250 |
+
|
251 |
+
@dataclass
|
252 |
+
class EnumOptional:
|
253 |
+
with_default: Optional[Color] = Color.BLUE
|
254 |
+
as_none: Optional[Color] = None
|
255 |
+
not_optional: Color = Color.BLUE
|
256 |
+
|
257 |
+
|
258 |
+
@dataclass
|
259 |
+
class DictOptional:
|
260 |
+
with_default: Optional[Dict[str, int]] = field(default_factory=lambda: {"a": 10})
|
261 |
+
as_none: Optional[Dict[str, int]] = None
|
262 |
+
not_optional: Dict[str, int] = field(default_factory=lambda: {"a": 10})
|
263 |
+
|
264 |
+
|
265 |
+
@dataclass
|
266 |
+
class StructuredOptional:
|
267 |
+
with_default: Optional[Nested] = Nested()
|
268 |
+
as_none: Optional[Nested] = None
|
269 |
+
not_optional: Nested = Nested()
|
270 |
+
|
271 |
+
|
272 |
+
@dataclass(frozen=True)
|
273 |
+
class FrozenClass:
|
274 |
+
user: User = User(name="Bart", age=10)
|
275 |
+
x: int = 10
|
276 |
+
list: List[int] = field(default_factory=lambda: [1, 2, 3])
|
277 |
+
|
278 |
+
|
279 |
+
@dataclass
|
280 |
+
class ContainsFrozen:
|
281 |
+
x: int = 10
|
282 |
+
frozen: FrozenClass = FrozenClass()
|
283 |
+
|
284 |
+
|
285 |
+
@dataclass
|
286 |
+
class WithTypedList:
|
287 |
+
list: List[int] = field(default_factory=lambda: [1, 2, 3])
|
288 |
+
|
289 |
+
|
290 |
+
@dataclass
|
291 |
+
class WithTypedDict:
|
292 |
+
dict: Dict[str, int] = field(default_factory=lambda: {"foo": 10, "bar": 20})
|
293 |
+
|
294 |
+
|
295 |
+
@dataclass
|
296 |
+
class ErrorDictIntKey:
|
297 |
+
# invalid dict key, must be str
|
298 |
+
dict: Dict[int, str] = field(default_factory=lambda: {10: "foo", 20: "bar"})
|
299 |
+
|
300 |
+
|
301 |
+
class RegularClass:
|
302 |
+
pass
|
303 |
+
|
304 |
+
|
305 |
+
@dataclass
|
306 |
+
class ErrorDictUnsupportedValue:
|
307 |
+
# invalid dict value type, not one of the supported types
|
308 |
+
dict: Dict[str, RegularClass] = field(default_factory=dict)
|
309 |
+
|
310 |
+
|
311 |
+
@dataclass
|
312 |
+
class ErrorListUnsupportedValue:
|
313 |
+
# invalid dict value type, not one of the supported types
|
314 |
+
dict: List[RegularClass] = field(default_factory=list)
|
315 |
+
|
316 |
+
|
317 |
+
@dataclass
|
318 |
+
class ErrorListUnsupportedStructuredConfig:
|
319 |
+
# Nesting of structured configs in Dict and List is not currently supported
|
320 |
+
list: List[User] = field(default_factory=list)
|
321 |
+
|
322 |
+
|
323 |
+
@dataclass
|
324 |
+
class ListExamples:
|
325 |
+
any: List[Any] = field(default_factory=lambda: [1, "foo"])
|
326 |
+
ints: List[int] = field(default_factory=lambda: [1, 2])
|
327 |
+
strings: List[str] = field(default_factory=lambda: ["foo", "bar"])
|
328 |
+
booleans: List[bool] = field(default_factory=lambda: [True, False])
|
329 |
+
colors: List[Color] = field(default_factory=lambda: [Color.RED, Color.GREEN])
|
330 |
+
|
331 |
+
|
332 |
+
@dataclass
|
333 |
+
class TupleExamples:
|
334 |
+
any: Tuple[Any, Any] = field(default_factory=lambda: (1, "foo"))
|
335 |
+
ints: Tuple[int, int] = field(default_factory=lambda: (1, 2))
|
336 |
+
strings: Tuple[str, str] = field(default_factory=lambda: ("foo", "bar"))
|
337 |
+
booleans: Tuple[bool, bool] = field(default_factory=lambda: (True, False))
|
338 |
+
colors: Tuple[Color, Color] = field(
|
339 |
+
default_factory=lambda: (Color.RED, Color.GREEN)
|
340 |
+
)
|
341 |
+
|
342 |
+
|
343 |
+
@dataclass
|
344 |
+
class DictExamples:
|
345 |
+
any: Dict[str, Any] = field(default_factory=lambda: {"a": 1, "b": "foo"})
|
346 |
+
ints: Dict[str, int] = field(default_factory=lambda: {"a": 10, "b": 20})
|
347 |
+
strings: Dict[str, str] = field(default_factory=lambda: {"a": "foo", "b": "bar"})
|
348 |
+
booleans: Dict[str, bool] = field(default_factory=lambda: {"a": True, "b": False})
|
349 |
+
colors: Dict[str, Color] = field(
|
350 |
+
default_factory=lambda: {
|
351 |
+
"red": Color.RED,
|
352 |
+
"green": Color.GREEN,
|
353 |
+
"blue": Color.BLUE,
|
354 |
+
}
|
355 |
+
)
|
356 |
+
|
357 |
+
|
358 |
+
@dataclass
|
359 |
+
class DictWithEnumKeys:
|
360 |
+
enum_key: Dict[Color, str] = field(
|
361 |
+
default_factory=lambda: {Color.RED: "red", Color.GREEN: "green"}
|
362 |
+
)
|
363 |
+
|
364 |
+
|
365 |
+
@dataclass
|
366 |
+
class DictOfObjects:
|
367 |
+
users: Dict[str, User] = field(
|
368 |
+
default_factory=lambda: {"joe": User(name="Joe", age=18)}
|
369 |
+
)
|
370 |
+
|
371 |
+
|
372 |
+
@dataclass
|
373 |
+
class ListOfObjects:
|
374 |
+
users: List[User] = field(default_factory=lambda: [User(name="Joe", age=18)])
|
375 |
+
|
376 |
+
|
377 |
+
class DictSubclass:
|
378 |
+
@dataclass
|
379 |
+
class Str2Str(Dict[str, str]):
|
380 |
+
pass
|
381 |
+
|
382 |
+
@dataclass
|
383 |
+
class Color2Str(Dict[Color, str]):
|
384 |
+
pass
|
385 |
+
|
386 |
+
@dataclass
|
387 |
+
class Color2Color(Dict[Color, Color]):
|
388 |
+
pass
|
389 |
+
|
390 |
+
@dataclass
|
391 |
+
class Str2User(Dict[str, User]):
|
392 |
+
pass
|
393 |
+
|
394 |
+
@dataclass
|
395 |
+
class Str2StrWithField(Dict[str, str]):
|
396 |
+
foo: str = "bar"
|
397 |
+
|
398 |
+
@dataclass
|
399 |
+
class Str2IntWithStrField(Dict[str, int]):
|
400 |
+
foo: str = "bar"
|
401 |
+
|
402 |
+
class Error:
|
403 |
+
@dataclass
|
404 |
+
class User2Str(Dict[User, str]):
|
405 |
+
pass
|
406 |
+
|
407 |
+
|
408 |
+
@dataclass
|
409 |
+
class Plugin:
|
410 |
+
name: str = MISSING
|
411 |
+
params: Any = MISSING
|
412 |
+
|
413 |
+
|
414 |
+
@dataclass
|
415 |
+
class ConcretePlugin(Plugin):
|
416 |
+
name: str = "foobar_plugin"
|
417 |
+
|
418 |
+
@dataclass
|
419 |
+
class FoobarParams:
|
420 |
+
foo: int = 10
|
421 |
+
|
422 |
+
params: FoobarParams = FoobarParams()
|
423 |
+
|
424 |
+
|
425 |
+
@dataclass
|
426 |
+
class PluginWithAdditionalField(Plugin):
|
427 |
+
name: str = "foobar2_plugin"
|
428 |
+
additional: int = 10
|
429 |
+
|
430 |
+
|
431 |
+
# Does not extend Plugin, cannot be assigned or merged
|
432 |
+
@dataclass
|
433 |
+
class FaultyPlugin:
|
434 |
+
name: str = "faulty_plugin"
|
435 |
+
|
436 |
+
|
437 |
+
@dataclass
|
438 |
+
class PluginHolder:
|
439 |
+
none: Optional[Plugin] = None
|
440 |
+
missing: Plugin = MISSING
|
441 |
+
plugin: Plugin = Plugin()
|
442 |
+
plugin2: Plugin = ConcretePlugin()
|
443 |
+
|
444 |
+
|
445 |
+
@dataclass
|
446 |
+
class LinkedList:
|
447 |
+
next: Optional["LinkedList"] = None
|
448 |
+
value: Any = MISSING
|
449 |
+
|
450 |
+
|
451 |
+
class MissingTest:
|
452 |
+
@dataclass
|
453 |
+
class Missing1:
|
454 |
+
head: LinkedList = MISSING
|
455 |
+
|
456 |
+
@dataclass
|
457 |
+
class Missing2:
|
458 |
+
head: LinkedList = LinkedList(next=MISSING, value=1)
|
459 |
+
|
460 |
+
|
461 |
+
@dataclass
|
462 |
+
class NestedWithNone:
|
463 |
+
plugin: Optional[Plugin] = None
|
464 |
+
|
465 |
+
|
466 |
+
@dataclass
|
467 |
+
class UnionError:
|
468 |
+
x: Union[int, str] = 10
|
469 |
+
|
470 |
+
|
471 |
+
@dataclass
|
472 |
+
class WithNativeMISSING:
|
473 |
+
num: int = dataclasses.MISSING # type: ignore
|
474 |
+
|
475 |
+
|
476 |
+
@dataclass
|
477 |
+
class MissingStructuredConfigField:
|
478 |
+
plugin: Plugin = MISSING
|
479 |
+
|
480 |
+
|
481 |
+
@dataclass
|
482 |
+
class ListClass:
|
483 |
+
list: List[int] = field(default_factory=lambda: [])
|
484 |
+
tuple: Tuple[int, int] = field(default_factory=lambda: (1, 2))
|
tests/structured_conf/test_structured_basic.py
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from importlib import import_module
|
3 |
+
from typing import Any, Optional
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from omegaconf import OmegaConf, ValidationError, _utils
|
8 |
+
from omegaconf.errors import ConfigKeyError
|
9 |
+
|
10 |
+
|
11 |
+
@pytest.mark.parametrize(
|
12 |
+
"class_type",
|
13 |
+
[
|
14 |
+
"tests.structured_conf.data.dataclasses",
|
15 |
+
"tests.structured_conf.data.attr_classes",
|
16 |
+
],
|
17 |
+
)
|
18 |
+
class TestStructured:
|
19 |
+
class TestBasic:
|
20 |
+
def test_error_on_non_structured_config_class(self, class_type: str) -> None:
|
21 |
+
module: Any = import_module(class_type)
|
22 |
+
with pytest.raises(ValidationError, match="structured config"):
|
23 |
+
OmegaConf.structured(module.NotStructuredConfig)
|
24 |
+
|
25 |
+
def test_error_on_non_structured_nested_config_class(
|
26 |
+
self, class_type: str
|
27 |
+
) -> None:
|
28 |
+
module: Any = import_module(class_type)
|
29 |
+
with pytest.raises(
|
30 |
+
ValidationError,
|
31 |
+
match=re.escape("Unexpected object type : NotStructuredConfig"),
|
32 |
+
):
|
33 |
+
OmegaConf.structured(module.StructuredWithInvalidField)
|
34 |
+
|
35 |
+
def test_assignment_of_subclass(self, class_type: str) -> None:
|
36 |
+
module: Any = import_module(class_type)
|
37 |
+
cfg = OmegaConf.create({"plugin": module.Plugin})
|
38 |
+
cfg.plugin = OmegaConf.structured(module.ConcretePlugin)
|
39 |
+
assert OmegaConf.get_type(cfg.plugin) == module.ConcretePlugin
|
40 |
+
assert (
|
41 |
+
OmegaConf.get_type(cfg.plugin.params)
|
42 |
+
== module.ConcretePlugin.FoobarParams
|
43 |
+
)
|
44 |
+
|
45 |
+
def test_assignment_of_non_subclass_1(self, class_type: str) -> None:
|
46 |
+
module: Any = import_module(class_type)
|
47 |
+
cfg = OmegaConf.create({"plugin": module.Plugin})
|
48 |
+
with pytest.raises(ValidationError):
|
49 |
+
cfg.plugin = OmegaConf.structured(module.FaultyPlugin)
|
50 |
+
|
51 |
+
def test_merge(self, class_type: str) -> None:
|
52 |
+
module: Any = import_module(class_type)
|
53 |
+
cfg1 = OmegaConf.create({"plugin": module.Plugin})
|
54 |
+
cfg2 = OmegaConf.create({"plugin": module.ConcretePlugin})
|
55 |
+
assert cfg2.plugin == module.ConcretePlugin
|
56 |
+
res: Any = OmegaConf.merge(cfg1, cfg2)
|
57 |
+
assert OmegaConf.get_type(res.plugin) == module.ConcretePlugin
|
58 |
+
assert (
|
59 |
+
OmegaConf.get_type(res.plugin.params)
|
60 |
+
== module.ConcretePlugin.FoobarParams
|
61 |
+
)
|
62 |
+
|
63 |
+
def test_merge_of_non_subclass_1(self, class_type: str) -> None:
|
64 |
+
module: Any = import_module(class_type)
|
65 |
+
cfg1 = OmegaConf.create({"plugin": module.Plugin})
|
66 |
+
cfg2 = OmegaConf.create({"plugin": module.FaultyPlugin})
|
67 |
+
with pytest.raises(ValidationError):
|
68 |
+
OmegaConf.merge(cfg1, cfg2)
|
69 |
+
|
70 |
+
def test_merge_error_new_attribute(self, class_type: str) -> None:
|
71 |
+
module: Any = import_module(class_type)
|
72 |
+
cfg = OmegaConf.structured(module.ConcretePlugin)
|
73 |
+
cfg2 = OmegaConf.create({"params": {"bar": 10}})
|
74 |
+
# raise if an invalid key is merged into a struct
|
75 |
+
with pytest.raises(ConfigKeyError):
|
76 |
+
OmegaConf.merge(cfg, cfg2)
|
77 |
+
|
78 |
+
def test_merge_error_override_bad_type(self, class_type: str) -> None:
|
79 |
+
module: Any = import_module(class_type)
|
80 |
+
cfg = OmegaConf.structured(module.ConcretePlugin)
|
81 |
+
|
82 |
+
# raise if an invalid key is merged into a struct
|
83 |
+
with pytest.raises(ValidationError):
|
84 |
+
OmegaConf.merge(cfg, {"params": {"foo": "zonk"}})
|
85 |
+
|
86 |
+
def test_error_message(self, class_type: str) -> None:
|
87 |
+
module: Any = import_module(class_type)
|
88 |
+
cfg = OmegaConf.structured(module.StructuredOptional)
|
89 |
+
msg = re.escape("child 'not_optional' is not Optional")
|
90 |
+
with pytest.raises(ValidationError, match=msg):
|
91 |
+
cfg.not_optional = None
|
92 |
+
|
93 |
+
def test_none_assignment(self, class_type: str) -> None:
|
94 |
+
module: Any = import_module(class_type)
|
95 |
+
cfg = OmegaConf.create({"plugin": module.Plugin})
|
96 |
+
# can assign None to params (type Any):
|
97 |
+
cfg.plugin.params = None
|
98 |
+
assert cfg.plugin.params is None
|
99 |
+
|
100 |
+
cfg2 = OmegaConf.create({"plugin": module.ConcretePlugin})
|
101 |
+
with pytest.raises(ValidationError):
|
102 |
+
cfg2.plugin.params = None
|
103 |
+
|
104 |
+
@pytest.mark.parametrize("rhs", [1, "foo"])
|
105 |
+
class TestFailedAssignmentOrMerges:
|
106 |
+
def test_assignment_of_non_subclass_2(self, class_type: str, rhs: Any) -> None:
|
107 |
+
module: Any = import_module(class_type)
|
108 |
+
cfg = OmegaConf.create({"plugin": module.Plugin})
|
109 |
+
with pytest.raises(ValidationError):
|
110 |
+
cfg.plugin = rhs
|
111 |
+
|
112 |
+
def test_merge_of_non_subclass_2(self, class_type: str, rhs: Any) -> None:
|
113 |
+
module: Any = import_module(class_type)
|
114 |
+
cfg1 = OmegaConf.create({"plugin": module.Plugin})
|
115 |
+
cfg2 = OmegaConf.create({"plugin": rhs})
|
116 |
+
with pytest.raises(ValidationError):
|
117 |
+
OmegaConf.merge(cfg1, cfg2)
|
118 |
+
|
119 |
+
def test_get_type(self, class_type: str) -> None:
|
120 |
+
module: Any = import_module(class_type)
|
121 |
+
cfg1 = OmegaConf.create(module.LinkedList)
|
122 |
+
assert OmegaConf.get_type(cfg1) == module.LinkedList
|
123 |
+
assert _utils.get_ref_type(cfg1, "next") == Optional[module.LinkedList]
|
124 |
+
assert OmegaConf.get_type(cfg1, "next") is None
|
125 |
+
|
126 |
+
assert cfg1.next is None
|
127 |
+
assert OmegaConf.is_missing(cfg1, "value")
|
128 |
+
|
129 |
+
cfg2 = OmegaConf.create(module.MissingTest.Missing1)
|
130 |
+
assert OmegaConf.is_missing(cfg2, "head")
|
131 |
+
assert _utils.get_ref_type(cfg2, "head") == module.LinkedList
|
132 |
+
assert OmegaConf.get_type(cfg2, "head") is None
|
133 |
+
|
134 |
+
class TestMissing:
|
135 |
+
def test_missing1(self, class_type: str) -> None:
|
136 |
+
module: Any = import_module(class_type)
|
137 |
+
cfg = OmegaConf.create(module.MissingTest.Missing1)
|
138 |
+
assert OmegaConf.is_missing(cfg, "head")
|
139 |
+
|
140 |
+
assert OmegaConf.get_type(cfg, "head") is None
|
141 |
+
|
142 |
+
with pytest.raises(ValidationError):
|
143 |
+
cfg.head = 10
|
144 |
+
|
145 |
+
def test_missing2(self, class_type: str) -> None:
|
146 |
+
module: Any = import_module(class_type)
|
147 |
+
cfg = OmegaConf.create(module.MissingTest.Missing2)
|
148 |
+
assert cfg == {"head": {"next": "???", "value": 1}}
|
149 |
+
assert OmegaConf.is_missing(cfg.head, "next")
|
150 |
+
|
151 |
+
cfg.head.next = module.LinkedList(value=2)
|
152 |
+
assert cfg == {"head": {"next": {"next": None, "value": 2}, "value": 1}}
|
153 |
+
|
154 |
+
def test_plugin_holder(self, class_type: str) -> None:
|
155 |
+
module: Any = import_module(class_type)
|
156 |
+
cfg = OmegaConf.create(module.PluginHolder)
|
157 |
+
|
158 |
+
assert OmegaConf.is_optional(cfg, "none")
|
159 |
+
assert _utils.get_ref_type(cfg, "none") == Optional[module.Plugin]
|
160 |
+
assert OmegaConf.get_type(cfg, "none") is None
|
161 |
+
|
162 |
+
assert not OmegaConf.is_optional(cfg, "missing")
|
163 |
+
assert _utils.get_ref_type(cfg, "missing") == module.Plugin
|
164 |
+
assert OmegaConf.get_type(cfg, "missing") is None
|
165 |
+
|
166 |
+
assert not OmegaConf.is_optional(cfg, "plugin")
|
167 |
+
assert _utils.get_ref_type(cfg, "plugin") == module.Plugin
|
168 |
+
assert OmegaConf.get_type(cfg, "plugin") == module.Plugin
|
169 |
+
|
170 |
+
cfg.plugin = module.ConcretePlugin()
|
171 |
+
assert not OmegaConf.is_optional(cfg, "plugin")
|
172 |
+
assert _utils.get_ref_type(cfg, "plugin") == module.Plugin
|
173 |
+
assert OmegaConf.get_type(cfg, "plugin") == module.ConcretePlugin
|
174 |
+
|
175 |
+
assert not OmegaConf.is_optional(cfg, "plugin2")
|
176 |
+
assert _utils.get_ref_type(cfg, "plugin2") == module.Plugin
|
177 |
+
assert OmegaConf.get_type(cfg, "plugin2") == module.ConcretePlugin
|
178 |
+
|
179 |
+
def test_plugin_merge(self, class_type: str) -> None:
|
180 |
+
module: Any = import_module(class_type)
|
181 |
+
plugin = OmegaConf.structured(module.Plugin)
|
182 |
+
concrete = OmegaConf.structured(module.ConcretePlugin)
|
183 |
+
ret = OmegaConf.merge(plugin, concrete)
|
184 |
+
assert ret == concrete
|
185 |
+
assert OmegaConf.get_type(ret) == module.ConcretePlugin
|
186 |
+
|
187 |
+
more_fields = OmegaConf.structured(module.PluginWithAdditionalField)
|
188 |
+
ret = OmegaConf.merge(plugin, more_fields)
|
189 |
+
assert ret == more_fields
|
190 |
+
assert OmegaConf.get_type(ret) == module.PluginWithAdditionalField
|
191 |
+
|
192 |
+
def test_native_missing(self, class_type: str) -> None:
|
193 |
+
module: Any = import_module(class_type)
|
194 |
+
with pytest.raises(
|
195 |
+
ValueError,
|
196 |
+
match=re.escape(
|
197 |
+
"Missing default value for WithNativeMISSING.num,"
|
198 |
+
" to indicate default must be populated later use OmegaConf.MISSING"
|
199 |
+
),
|
200 |
+
):
|
201 |
+
OmegaConf.create(module.WithNativeMISSING)
|
tests/structured_conf/test_structured_config.py
ADDED
@@ -0,0 +1,983 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from importlib import import_module
|
3 |
+
from typing import Any, Dict, Optional
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from omegaconf import (
|
8 |
+
MISSING,
|
9 |
+
AnyNode,
|
10 |
+
DictConfig,
|
11 |
+
KeyValidationError,
|
12 |
+
MissingMandatoryValue,
|
13 |
+
OmegaConf,
|
14 |
+
ReadonlyConfigError,
|
15 |
+
ValidationError,
|
16 |
+
_utils,
|
17 |
+
)
|
18 |
+
from omegaconf.errors import ConfigKeyError
|
19 |
+
from tests import Color
|
20 |
+
|
21 |
+
|
22 |
+
class EnumConfigAssignments:
|
23 |
+
legal = [
|
24 |
+
(Color.RED, Color.RED),
|
25 |
+
(Color.GREEN, Color.GREEN),
|
26 |
+
(Color.BLUE, Color.BLUE),
|
27 |
+
("RED", Color.RED),
|
28 |
+
("GREEN", Color.GREEN),
|
29 |
+
("BLUE", Color.BLUE),
|
30 |
+
("Color.RED", Color.RED),
|
31 |
+
("Color.GREEN", Color.GREEN),
|
32 |
+
("Color.BLUE", Color.BLUE),
|
33 |
+
(1, Color.RED),
|
34 |
+
(2, Color.GREEN),
|
35 |
+
(3, Color.BLUE),
|
36 |
+
]
|
37 |
+
illegal = ["foo", True, False, 4, 1.0]
|
38 |
+
|
39 |
+
|
40 |
+
class IntegersConfigAssignments:
|
41 |
+
legal = [("10", 10), ("-10", -10), 100, 0, 1, 1]
|
42 |
+
illegal = ["foo", 1.0, float("inf"), float("nan"), Color.BLUE]
|
43 |
+
|
44 |
+
|
45 |
+
class StringConfigAssignments:
|
46 |
+
legal = ["10", "-10", "foo", "", (Color.BLUE, "Color.BLUE")]
|
47 |
+
illegal: Any = []
|
48 |
+
|
49 |
+
|
50 |
+
class FloatConfigAssignments:
|
51 |
+
legal = [
|
52 |
+
("inf", float("inf")),
|
53 |
+
("-inf", float("-inf")),
|
54 |
+
(10, 10.0),
|
55 |
+
(10.1, 10.1),
|
56 |
+
("10.2", 10.2),
|
57 |
+
("10e-3", 10e-3),
|
58 |
+
]
|
59 |
+
illegal = ["foo", True, False, Color.BLUE]
|
60 |
+
|
61 |
+
|
62 |
+
class BoolConfigAssignments:
|
63 |
+
legal = [
|
64 |
+
(True, True),
|
65 |
+
("Y", True),
|
66 |
+
("true", True),
|
67 |
+
("Yes", True),
|
68 |
+
("On", True),
|
69 |
+
("1", True),
|
70 |
+
(100, True),
|
71 |
+
(False, False),
|
72 |
+
("N", False),
|
73 |
+
("false", False),
|
74 |
+
("No", False),
|
75 |
+
("Off", False),
|
76 |
+
("0", False),
|
77 |
+
(0, False),
|
78 |
+
]
|
79 |
+
illegal = [100.0, Color.BLUE]
|
80 |
+
|
81 |
+
|
82 |
+
class AnyTypeConfigAssignments:
|
83 |
+
legal = [True, False, 10, 10.0, "foobar", Color.BLUE]
|
84 |
+
|
85 |
+
illegal: Any = []
|
86 |
+
|
87 |
+
|
88 |
+
@pytest.mark.parametrize(
|
89 |
+
"class_type",
|
90 |
+
[
|
91 |
+
"tests.structured_conf.data.dataclasses",
|
92 |
+
"tests.structured_conf.data.attr_classes",
|
93 |
+
],
|
94 |
+
)
|
95 |
+
class TestConfigs:
|
96 |
+
def test_nested_config_is_none(self, class_type: str) -> None:
|
97 |
+
module: Any = import_module(class_type)
|
98 |
+
cfg = OmegaConf.structured(module.NestedWithNone)
|
99 |
+
assert cfg == {"plugin": None}
|
100 |
+
assert OmegaConf.get_type(cfg, "plugin") is None
|
101 |
+
assert _utils.get_ref_type(cfg, "plugin") == Optional[module.Plugin]
|
102 |
+
|
103 |
+
def test_nested_config(self, class_type: str) -> None:
|
104 |
+
module: Any = import_module(class_type)
|
105 |
+
|
106 |
+
def validate(cfg: DictConfig) -> None:
|
107 |
+
assert cfg == {
|
108 |
+
"default_value": {
|
109 |
+
"with_default": 10,
|
110 |
+
"null_default": None,
|
111 |
+
"mandatory_missing": "???",
|
112 |
+
"interpolation": "${value_at_root}",
|
113 |
+
},
|
114 |
+
"user_provided_default": {
|
115 |
+
"with_default": 42,
|
116 |
+
"null_default": None,
|
117 |
+
"mandatory_missing": "???",
|
118 |
+
"interpolation": "${value_at_root}",
|
119 |
+
},
|
120 |
+
"value_at_root": 1000,
|
121 |
+
}
|
122 |
+
|
123 |
+
with pytest.raises(ValidationError):
|
124 |
+
cfg.user_provided_default = 10
|
125 |
+
|
126 |
+
with pytest.raises(ValidationError):
|
127 |
+
cfg.default_value = 10
|
128 |
+
|
129 |
+
# assign subclass
|
130 |
+
cfg.default_value = module.NestedSubclass()
|
131 |
+
assert cfg.default_value == {
|
132 |
+
"additional": 20,
|
133 |
+
"with_default": 10,
|
134 |
+
"null_default": None,
|
135 |
+
"mandatory_missing": "???",
|
136 |
+
"interpolation": "${value_at_root}",
|
137 |
+
}
|
138 |
+
|
139 |
+
# assign original ref type back
|
140 |
+
cfg.default_value = module.Nested()
|
141 |
+
assert cfg.default_value == module.Nested()
|
142 |
+
|
143 |
+
with pytest.warns(UserWarning):
|
144 |
+
conf1 = OmegaConf.structured(module.NestedConfig)
|
145 |
+
validate(conf1)
|
146 |
+
conf1 = OmegaConf.structured(module.NestedConfig(default_value=module.Nested()))
|
147 |
+
validate(conf1)
|
148 |
+
|
149 |
+
def test_value_without_a_default(self, class_type: str) -> None:
|
150 |
+
module: Any = import_module(class_type)
|
151 |
+
with pytest.raises(
|
152 |
+
ValueError,
|
153 |
+
match=re.escape(
|
154 |
+
"Missing default value for NoDefaultErrors.no_default,"
|
155 |
+
" to indicate default must be populated later use OmegaConf.MISSING"
|
156 |
+
),
|
157 |
+
):
|
158 |
+
OmegaConf.structured(module.NoDefaultErrors)
|
159 |
+
|
160 |
+
OmegaConf.structured(module.NoDefaultErrors(no_default=10)) == {
|
161 |
+
"no_default": 10
|
162 |
+
}
|
163 |
+
|
164 |
+
def test_union_errors(self, class_type: str) -> None:
|
165 |
+
module: Any = import_module(class_type)
|
166 |
+
with pytest.raises(ValueError):
|
167 |
+
OmegaConf.structured(module.UnionError)
|
168 |
+
|
169 |
+
def test_config_with_list(self, class_type: str) -> None:
|
170 |
+
module: Any = import_module(class_type)
|
171 |
+
|
172 |
+
def validate(cfg: DictConfig) -> None:
|
173 |
+
assert cfg == {"list1": [1, 2, 3], "list2": [1, 2, 3], "missing": MISSING}
|
174 |
+
with pytest.raises(ValidationError):
|
175 |
+
cfg.list1[1] = "foo"
|
176 |
+
|
177 |
+
assert OmegaConf.is_missing(cfg, "missing")
|
178 |
+
|
179 |
+
conf1 = OmegaConf.structured(module.ConfigWithList)
|
180 |
+
validate(conf1)
|
181 |
+
|
182 |
+
conf1 = OmegaConf.structured(module.ConfigWithList())
|
183 |
+
validate(conf1)
|
184 |
+
|
185 |
+
def test_assignment_to_nested_structured_config(self, class_type: str) -> None:
|
186 |
+
module: Any = import_module(class_type)
|
187 |
+
with pytest.warns(UserWarning):
|
188 |
+
conf = OmegaConf.structured(module.NestedConfig)
|
189 |
+
with pytest.raises(ValidationError):
|
190 |
+
conf.default_value = 10
|
191 |
+
|
192 |
+
conf.default_value = module.Nested()
|
193 |
+
|
194 |
+
def test_assignment_to_structured_inside_dict_config(self, class_type: str) -> None:
|
195 |
+
module: Any = import_module(class_type)
|
196 |
+
conf = OmegaConf.create({"val": module.Nested})
|
197 |
+
with pytest.raises(ValidationError):
|
198 |
+
conf.val = 10
|
199 |
+
|
200 |
+
def test_config_with_dict(self, class_type: str) -> None:
|
201 |
+
module: Any = import_module(class_type)
|
202 |
+
|
203 |
+
def validate(cfg: DictConfig) -> None:
|
204 |
+
assert cfg == {"dict1": {"foo": "bar"}, "missing": MISSING}
|
205 |
+
assert OmegaConf.is_missing(cfg, "missing")
|
206 |
+
|
207 |
+
conf1 = OmegaConf.structured(module.ConfigWithDict)
|
208 |
+
validate(conf1)
|
209 |
+
conf1 = OmegaConf.structured(module.ConfigWithDict())
|
210 |
+
validate(conf1)
|
211 |
+
|
212 |
+
def test_structured_config_struct_behavior(self, class_type: str) -> None:
|
213 |
+
module: Any = import_module(class_type)
|
214 |
+
|
215 |
+
def validate(cfg: DictConfig) -> None:
|
216 |
+
assert not OmegaConf.is_struct(cfg)
|
217 |
+
with pytest.raises(AttributeError):
|
218 |
+
# noinspection PyStatementEffect
|
219 |
+
cfg.foo
|
220 |
+
|
221 |
+
cfg.dict1.foo = 10
|
222 |
+
assert cfg.dict1.foo == 10
|
223 |
+
|
224 |
+
# setting struct False on a specific typed node opens it up even though it's
|
225 |
+
# still typed
|
226 |
+
OmegaConf.set_struct(cfg, False)
|
227 |
+
cfg.foo = 20
|
228 |
+
assert cfg.foo == 20
|
229 |
+
|
230 |
+
conf = OmegaConf.structured(module.ConfigWithDict)
|
231 |
+
validate(conf)
|
232 |
+
conf = OmegaConf.structured(module.ConfigWithDict())
|
233 |
+
validate(conf)
|
234 |
+
|
235 |
+
@pytest.mark.parametrize( # type:ignore
|
236 |
+
"tested_type,assignment_data, init_dict",
|
237 |
+
[
|
238 |
+
# Use class to build config
|
239 |
+
("BoolConfig", BoolConfigAssignments, {}),
|
240 |
+
("IntegersConfig", IntegersConfigAssignments, {}),
|
241 |
+
("FloatConfig", FloatConfigAssignments, {}),
|
242 |
+
("StringConfig", StringConfigAssignments, {}),
|
243 |
+
("EnumConfig", EnumConfigAssignments, {}),
|
244 |
+
# Use instance to build config
|
245 |
+
("BoolConfig", BoolConfigAssignments, {"with_default": False}),
|
246 |
+
("IntegersConfig", IntegersConfigAssignments, {"with_default": 42}),
|
247 |
+
("FloatConfig", FloatConfigAssignments, {"with_default": 42.0}),
|
248 |
+
("StringConfig", StringConfigAssignments, {"with_default": "fooooooo"}),
|
249 |
+
("EnumConfig", EnumConfigAssignments, {"with_default": Color.BLUE}),
|
250 |
+
("AnyTypeConfig", AnyTypeConfigAssignments, {}),
|
251 |
+
],
|
252 |
+
)
|
253 |
+
def test_field_with_default_value(
|
254 |
+
self,
|
255 |
+
class_type: str,
|
256 |
+
tested_type: str,
|
257 |
+
init_dict: Dict[str, Any],
|
258 |
+
assignment_data: Any,
|
259 |
+
) -> None:
|
260 |
+
module: Any = import_module(class_type)
|
261 |
+
input_class = getattr(module, tested_type)
|
262 |
+
|
263 |
+
def validate(input_: Any, expected: Any) -> None:
|
264 |
+
conf = OmegaConf.structured(input_)
|
265 |
+
# Test access
|
266 |
+
assert conf.with_default == expected.with_default
|
267 |
+
assert conf.null_default is None
|
268 |
+
# Test that accessing a variable without a default value
|
269 |
+
# results in a MissingMandatoryValue exception
|
270 |
+
with pytest.raises(MissingMandatoryValue):
|
271 |
+
# noinspection PyStatementEffect
|
272 |
+
conf.mandatory_missing
|
273 |
+
|
274 |
+
# Test interpolation preserves type and value
|
275 |
+
assert type(conf.with_default) == type(conf.interpolation) # noqa E721
|
276 |
+
assert conf.with_default == conf.interpolation
|
277 |
+
|
278 |
+
# Test that assignment of illegal values
|
279 |
+
for illegal_value in assignment_data.illegal:
|
280 |
+
with pytest.raises(ValidationError):
|
281 |
+
conf.with_default = illegal_value
|
282 |
+
|
283 |
+
with pytest.raises(ValidationError):
|
284 |
+
conf.null_default = illegal_value
|
285 |
+
|
286 |
+
with pytest.raises(ValidationError):
|
287 |
+
conf.mandatory_missing = illegal_value
|
288 |
+
|
289 |
+
# Test assignment of legal values
|
290 |
+
for legal_value in assignment_data.legal:
|
291 |
+
expected_data = legal_value
|
292 |
+
if isinstance(legal_value, tuple):
|
293 |
+
expected_data = legal_value[1]
|
294 |
+
legal_value = legal_value[0]
|
295 |
+
conf.with_default = legal_value
|
296 |
+
conf.null_default = legal_value
|
297 |
+
conf.mandatory_missing = legal_value
|
298 |
+
|
299 |
+
msg = "Error: {} : {}".format(input_class.__name__, legal_value)
|
300 |
+
assert conf.with_default == expected_data, msg
|
301 |
+
assert conf.null_default == expected_data, msg
|
302 |
+
assert conf.mandatory_missing == expected_data, msg
|
303 |
+
|
304 |
+
validate(input_class, input_class())
|
305 |
+
validate(input_class(**init_dict), input_class(**init_dict))
|
306 |
+
|
307 |
+
@pytest.mark.parametrize( # type: ignore
|
308 |
+
"input_init, expected_init",
|
309 |
+
[
|
310 |
+
# attr class as class
|
311 |
+
(None, {}),
|
312 |
+
# attr class object with custom values
|
313 |
+
({"int_default": 30}, {"int_default": 30}),
|
314 |
+
# dataclass as class
|
315 |
+
(None, {}),
|
316 |
+
# dataclass as object with custom values
|
317 |
+
({"int_default": 30}, {"int_default": 30}),
|
318 |
+
],
|
319 |
+
)
|
320 |
+
def test_untyped(
|
321 |
+
self, class_type: str, input_init: Any, expected_init: Any
|
322 |
+
) -> None:
|
323 |
+
module: Any = import_module(class_type)
|
324 |
+
input_ = module.AnyTypeConfig
|
325 |
+
expected = input_(**expected_init)
|
326 |
+
if input_init is not None:
|
327 |
+
input_ = input_(**input_init)
|
328 |
+
|
329 |
+
conf = OmegaConf.structured(input_)
|
330 |
+
assert conf.null_default == expected.null_default
|
331 |
+
assert conf.int_default == expected.int_default
|
332 |
+
assert conf.float_default == expected.float_default
|
333 |
+
assert conf.str_default == expected.str_default
|
334 |
+
assert conf.bool_default == expected.bool_default
|
335 |
+
# yes, this is weird.
|
336 |
+
assert "mandatory_missing" in conf.keys() and "mandatory_missing" not in conf
|
337 |
+
|
338 |
+
with pytest.raises(MissingMandatoryValue):
|
339 |
+
# noinspection PyStatementEffect
|
340 |
+
conf.mandatory_missing
|
341 |
+
|
342 |
+
assert type(conf._get_node("null_default")) == AnyNode
|
343 |
+
assert type(conf._get_node("int_default")) == AnyNode
|
344 |
+
assert type(conf._get_node("float_default")) == AnyNode
|
345 |
+
assert type(conf._get_node("str_default")) == AnyNode
|
346 |
+
assert type(conf._get_node("bool_default")) == AnyNode
|
347 |
+
assert type(conf._get_node("mandatory_missing")) == AnyNode
|
348 |
+
|
349 |
+
assert conf.int_default == expected.int_default
|
350 |
+
with pytest.raises(ValidationError):
|
351 |
+
conf.typed_int_default = "foo"
|
352 |
+
|
353 |
+
values = [10, True, False, None, 1.0, -1.0, "10", float("inf")]
|
354 |
+
for val in values:
|
355 |
+
conf.null_default = val
|
356 |
+
conf.int_default = val
|
357 |
+
conf.float_default = val
|
358 |
+
conf.str_default = val
|
359 |
+
conf.bool_default = val
|
360 |
+
|
361 |
+
assert conf.null_default == val
|
362 |
+
assert conf.int_default == val
|
363 |
+
assert conf.float_default == val
|
364 |
+
assert conf.str_default == val
|
365 |
+
assert conf.bool_default == val
|
366 |
+
|
367 |
+
def test_interpolation(self, class_type: str) -> Any:
|
368 |
+
module: Any = import_module(class_type)
|
369 |
+
input_ = module.Interpolation()
|
370 |
+
conf = OmegaConf.structured(input_)
|
371 |
+
assert conf.x == input_.x
|
372 |
+
assert conf.z1 == conf.x
|
373 |
+
assert conf.z2 == f"{conf.x}_{conf.y}"
|
374 |
+
assert type(conf.x) == int
|
375 |
+
assert type(conf.y) == int
|
376 |
+
assert type(conf.z1) == int
|
377 |
+
assert type(conf.z2) == str
|
378 |
+
|
379 |
+
@pytest.mark.parametrize( # type: ignore
|
380 |
+
"tested_type",
|
381 |
+
[
|
382 |
+
"BoolOptional",
|
383 |
+
"IntegerOptional",
|
384 |
+
"FloatOptional",
|
385 |
+
"StringOptional",
|
386 |
+
"ListOptional",
|
387 |
+
"TupleOptional",
|
388 |
+
"EnumOptional",
|
389 |
+
"StructuredOptional",
|
390 |
+
"DictOptional",
|
391 |
+
],
|
392 |
+
)
|
393 |
+
def test_optional(self, class_type: str, tested_type: str) -> None:
|
394 |
+
module: Any = import_module(class_type)
|
395 |
+
input_ = getattr(module, tested_type)
|
396 |
+
obj = input_()
|
397 |
+
conf = OmegaConf.structured(input_)
|
398 |
+
|
399 |
+
# verify non-optional fields are rejecting None
|
400 |
+
with pytest.raises(ValidationError):
|
401 |
+
conf.not_optional = None
|
402 |
+
|
403 |
+
assert conf.as_none is None
|
404 |
+
assert conf.with_default == obj.with_default
|
405 |
+
# assign None to an optional field
|
406 |
+
conf.with_default = None
|
407 |
+
assert conf.with_default is None
|
408 |
+
|
409 |
+
def test_typed_list(self, class_type: str) -> None:
|
410 |
+
module: Any = import_module(class_type)
|
411 |
+
input_ = module.WithTypedList
|
412 |
+
conf = OmegaConf.structured(input_)
|
413 |
+
with pytest.raises(ValidationError):
|
414 |
+
conf.list[0] = "fail"
|
415 |
+
|
416 |
+
with pytest.raises(ValidationError):
|
417 |
+
conf.list.append("fail")
|
418 |
+
|
419 |
+
with pytest.raises(ValidationError):
|
420 |
+
cfg2 = OmegaConf.create({"list": ["fail"]})
|
421 |
+
OmegaConf.merge(conf, cfg2)
|
422 |
+
|
423 |
+
def test_typed_dict(self, class_type: str) -> None:
|
424 |
+
module: Any = import_module(class_type)
|
425 |
+
input_ = module.WithTypedDict
|
426 |
+
conf = OmegaConf.structured(input_)
|
427 |
+
with pytest.raises(ValidationError):
|
428 |
+
conf.dict["foo"] = "fail"
|
429 |
+
|
430 |
+
with pytest.raises(ValidationError):
|
431 |
+
OmegaConf.merge(conf, OmegaConf.create({"dict": {"foo": "fail"}}))
|
432 |
+
|
433 |
+
def test_merged_type1(self, class_type: str) -> None:
|
434 |
+
# Test that the merged type is that of the last merged config
|
435 |
+
module: Any = import_module(class_type)
|
436 |
+
input_ = module.WithTypedDict
|
437 |
+
conf = OmegaConf.structured(input_)
|
438 |
+
res = OmegaConf.merge(OmegaConf.create(), conf)
|
439 |
+
assert OmegaConf.get_type(res) == input_
|
440 |
+
|
441 |
+
def test_merged_type2(self, class_type: str) -> None:
|
442 |
+
# Test that the merged type is that of the last merged config
|
443 |
+
module: Any = import_module(class_type)
|
444 |
+
input_ = module.WithTypedDict
|
445 |
+
conf = OmegaConf.structured(input_)
|
446 |
+
res = OmegaConf.merge(conf, {"dict": {"foo": 99}})
|
447 |
+
assert OmegaConf.get_type(res) == input_
|
448 |
+
|
449 |
+
def test_merged_with_subclass(self, class_type: str) -> None:
|
450 |
+
# Test that the merged type is that of the last merged config
|
451 |
+
module: Any = import_module(class_type)
|
452 |
+
c1 = OmegaConf.structured(module.Plugin)
|
453 |
+
c2 = OmegaConf.structured(module.ConcretePlugin)
|
454 |
+
res = OmegaConf.merge(c1, c2)
|
455 |
+
assert OmegaConf.get_type(res) == module.ConcretePlugin
|
456 |
+
|
457 |
+
def test_merge_missing_structured_config_is_missing(self, class_type: str) -> None:
|
458 |
+
# Test that the merged type is that of the last merged config
|
459 |
+
module: Any = import_module(class_type)
|
460 |
+
c1 = OmegaConf.structured(module.MissingStructuredConfigField)
|
461 |
+
assert OmegaConf.is_missing(c1, "plugin")
|
462 |
+
c2 = OmegaConf.merge(c1, module.MissingStructuredConfigField)
|
463 |
+
assert OmegaConf.is_missing(c2, "plugin")
|
464 |
+
|
465 |
+
def test_merge_none_is_none(self, class_type: str) -> None:
|
466 |
+
# Test that the merged type is that of the last merged config
|
467 |
+
module: Any = import_module(class_type)
|
468 |
+
c1 = OmegaConf.structured(module.StructuredOptional)
|
469 |
+
assert c1.with_default == module.Nested()
|
470 |
+
c2 = OmegaConf.merge(c1, {"with_default": None})
|
471 |
+
assert OmegaConf.is_none(c2, "with_default")
|
472 |
+
|
473 |
+
def test_merge_with_subclass_into_missing(self, class_type: str) -> None:
|
474 |
+
module: Any = import_module(class_type)
|
475 |
+
base = OmegaConf.structured(module.PluginHolder)
|
476 |
+
assert _utils.get_ref_type(base, "missing") == module.Plugin
|
477 |
+
assert OmegaConf.get_type(base, "missing") is None
|
478 |
+
res = OmegaConf.merge(base, {"missing": module.Plugin})
|
479 |
+
assert OmegaConf.get_type(res) == module.PluginHolder
|
480 |
+
assert _utils.get_ref_type(base, "missing") == module.Plugin
|
481 |
+
assert OmegaConf.get_type(res, "missing") == module.Plugin
|
482 |
+
|
483 |
+
def test_merged_with_nons_subclass(self, class_type: str) -> None:
|
484 |
+
module: Any = import_module(class_type)
|
485 |
+
c1 = OmegaConf.structured(module.Plugin)
|
486 |
+
c2 = OmegaConf.structured(module.FaultyPlugin)
|
487 |
+
with pytest.raises(ValidationError):
|
488 |
+
OmegaConf.merge(c1, c2)
|
489 |
+
|
490 |
+
def test_merge_into_Dict(self, class_type: str) -> None:
|
491 |
+
module: Any = import_module(class_type)
|
492 |
+
cfg = OmegaConf.structured(module.DictExamples)
|
493 |
+
res = OmegaConf.merge(cfg, {"strings": {"x": "abc"}})
|
494 |
+
assert res.strings == {"a": "foo", "b": "bar", "x": "abc"}
|
495 |
+
|
496 |
+
def test_merge_user_list_with_wrong_key(self, class_type: str) -> None:
|
497 |
+
module: Any = import_module(class_type)
|
498 |
+
cfg = OmegaConf.structured(module.UserList)
|
499 |
+
with pytest.raises(ConfigKeyError):
|
500 |
+
OmegaConf.merge(cfg, {"list": [{"foo": "var"}]})
|
501 |
+
|
502 |
+
def test_merge_list_with_correct_type(self, class_type: str) -> None:
|
503 |
+
module: Any = import_module(class_type)
|
504 |
+
cfg = OmegaConf.structured(module.UserList)
|
505 |
+
user = module.User(name="John", age=21)
|
506 |
+
res = OmegaConf.merge(cfg, {"list": [user]})
|
507 |
+
assert res.list == [user]
|
508 |
+
|
509 |
+
def test_merge_dict_with_wrong_type(self, class_type: str) -> None:
|
510 |
+
module: Any = import_module(class_type)
|
511 |
+
cfg = OmegaConf.structured(module.UserDict)
|
512 |
+
with pytest.raises(ValidationError):
|
513 |
+
OmegaConf.merge(cfg, {"dict": {"foo": "var"}})
|
514 |
+
|
515 |
+
def test_merge_dict_with_correct_type(self, class_type: str) -> None:
|
516 |
+
module: Any = import_module(class_type)
|
517 |
+
cfg = OmegaConf.structured(module.UserDict)
|
518 |
+
user = module.User(name="John", age=21)
|
519 |
+
res = OmegaConf.merge(cfg, {"dict": {"foo": user}})
|
520 |
+
assert res.dict == {"foo": user}
|
521 |
+
|
522 |
+
def test_typed_dict_key_error(self, class_type: str) -> None:
|
523 |
+
module: Any = import_module(class_type)
|
524 |
+
input_ = module.ErrorDictIntKey
|
525 |
+
with pytest.raises(KeyValidationError):
|
526 |
+
OmegaConf.structured(input_)
|
527 |
+
|
528 |
+
def test_typed_dict_value_error(self, class_type: str) -> None:
|
529 |
+
module: Any = import_module(class_type)
|
530 |
+
input_ = module.ErrorDictUnsupportedValue
|
531 |
+
with pytest.raises(ValidationError):
|
532 |
+
OmegaConf.structured(input_)
|
533 |
+
|
534 |
+
def test_typed_list_value_error(self, class_type: str) -> None:
|
535 |
+
module: Any = import_module(class_type)
|
536 |
+
input_ = module.ErrorListUnsupportedValue
|
537 |
+
with pytest.raises(ValidationError):
|
538 |
+
OmegaConf.structured(input_)
|
539 |
+
|
540 |
+
@pytest.mark.parametrize( # type: ignore
|
541 |
+
"example", ["ListExamples", "TupleExamples"]
|
542 |
+
)
|
543 |
+
def test_list_examples(self, class_type: str, example: str) -> None:
|
544 |
+
module: Any = import_module(class_type)
|
545 |
+
input_ = getattr(module, example)
|
546 |
+
conf = OmegaConf.structured(input_)
|
547 |
+
|
548 |
+
def test_any(name: str) -> None:
|
549 |
+
conf[name].append(True)
|
550 |
+
conf[name].extend([Color.RED, 3.1415])
|
551 |
+
conf[name][2] = False
|
552 |
+
assert conf[name] == [1, "foo", False, Color.RED, 3.1415]
|
553 |
+
|
554 |
+
# any and untyped
|
555 |
+
test_any("any")
|
556 |
+
|
557 |
+
# test ints
|
558 |
+
with pytest.raises(ValidationError):
|
559 |
+
conf.ints[0] = "foo"
|
560 |
+
conf.ints.append(10)
|
561 |
+
assert conf.ints == [1, 2, 10]
|
562 |
+
|
563 |
+
# test strings
|
564 |
+
conf.strings.append(Color.BLUE)
|
565 |
+
assert conf.strings == ["foo", "bar", "Color.BLUE"]
|
566 |
+
|
567 |
+
# test booleans
|
568 |
+
with pytest.raises(ValidationError):
|
569 |
+
conf.booleans[0] = "foo"
|
570 |
+
conf.booleans.append(True)
|
571 |
+
conf.booleans.append("off")
|
572 |
+
conf.booleans.append(1)
|
573 |
+
assert conf.booleans == [True, False, True, False, True]
|
574 |
+
|
575 |
+
# test colors
|
576 |
+
with pytest.raises(ValidationError):
|
577 |
+
conf.colors[0] = "foo"
|
578 |
+
conf.colors.append(Color.BLUE)
|
579 |
+
conf.colors.append("RED")
|
580 |
+
conf.colors.append("Color.GREEN")
|
581 |
+
conf.colors.append(3)
|
582 |
+
assert conf.colors == [
|
583 |
+
Color.RED,
|
584 |
+
Color.GREEN,
|
585 |
+
Color.BLUE,
|
586 |
+
Color.RED,
|
587 |
+
Color.GREEN,
|
588 |
+
Color.BLUE,
|
589 |
+
]
|
590 |
+
|
591 |
+
def test_dict_examples(self, class_type: str) -> None:
|
592 |
+
module: Any = import_module(class_type)
|
593 |
+
conf = OmegaConf.structured(module.DictExamples)
|
594 |
+
|
595 |
+
def test_any(name: str) -> None:
|
596 |
+
conf[name].c = True
|
597 |
+
conf[name].d = Color.RED
|
598 |
+
conf[name].e = 3.1415
|
599 |
+
assert conf[name] == {
|
600 |
+
"a": 1,
|
601 |
+
"b": "foo",
|
602 |
+
"c": True,
|
603 |
+
"d": Color.RED,
|
604 |
+
"e": 3.1415,
|
605 |
+
}
|
606 |
+
|
607 |
+
# any and untyped
|
608 |
+
test_any("any")
|
609 |
+
|
610 |
+
# test ints
|
611 |
+
with pytest.raises(ValidationError):
|
612 |
+
conf.ints.a = "foo"
|
613 |
+
conf.ints.c = 10
|
614 |
+
assert conf.ints == {"a": 10, "b": 20, "c": 10}
|
615 |
+
|
616 |
+
# test strings
|
617 |
+
conf.strings.c = Color.BLUE
|
618 |
+
assert conf.strings == {"a": "foo", "b": "bar", "c": "Color.BLUE"}
|
619 |
+
|
620 |
+
# tests booleans
|
621 |
+
with pytest.raises(ValidationError):
|
622 |
+
conf.booleans.a = "foo"
|
623 |
+
conf.booleans.c = True
|
624 |
+
conf.booleans.d = "off"
|
625 |
+
conf.booleans.e = 1
|
626 |
+
assert conf.booleans == {
|
627 |
+
"a": True,
|
628 |
+
"b": False,
|
629 |
+
"c": True,
|
630 |
+
"d": False,
|
631 |
+
"e": True,
|
632 |
+
}
|
633 |
+
|
634 |
+
# test colors
|
635 |
+
with pytest.raises(ValidationError):
|
636 |
+
conf.colors.foo = "foo"
|
637 |
+
conf.colors.c = Color.BLUE
|
638 |
+
conf.colors.d = "RED"
|
639 |
+
conf.colors.e = "Color.GREEN"
|
640 |
+
conf.colors.f = 3
|
641 |
+
assert conf.colors == {
|
642 |
+
"red": Color.RED,
|
643 |
+
"green": Color.GREEN,
|
644 |
+
"blue": Color.BLUE,
|
645 |
+
"c": Color.BLUE,
|
646 |
+
"d": Color.RED,
|
647 |
+
"e": Color.GREEN,
|
648 |
+
"f": Color.BLUE,
|
649 |
+
}
|
650 |
+
|
651 |
+
def test_enum_key(self, class_type: str) -> None:
|
652 |
+
module: Any = import_module(class_type)
|
653 |
+
conf = OmegaConf.structured(module.DictWithEnumKeys)
|
654 |
+
|
655 |
+
# When an Enum is a dictionary key the name of the Enum is actually used
|
656 |
+
# as the key
|
657 |
+
assert conf.enum_key.RED == "red"
|
658 |
+
assert conf.enum_key["GREEN"] == "green"
|
659 |
+
assert conf.enum_key[Color.GREEN] == "green"
|
660 |
+
|
661 |
+
conf.enum_key["BLUE"] = "Blue too"
|
662 |
+
assert conf.enum_key[Color.BLUE] == "Blue too"
|
663 |
+
with pytest.raises(KeyValidationError):
|
664 |
+
conf.enum_key["error"] = "error"
|
665 |
+
|
666 |
+
def test_dict_of_objects(self, class_type: str) -> None:
|
667 |
+
module: Any = import_module(class_type)
|
668 |
+
conf = OmegaConf.structured(module.DictOfObjects)
|
669 |
+
assert conf.users.joe.age == 18
|
670 |
+
assert conf.users.joe.name == "Joe"
|
671 |
+
|
672 |
+
conf.users.bond = module.User(name="James Bond", age=7)
|
673 |
+
assert conf.users.bond.name == "James Bond"
|
674 |
+
assert conf.users.bond.age == 7
|
675 |
+
|
676 |
+
with pytest.raises(ValidationError):
|
677 |
+
conf.users.fail = "fail"
|
678 |
+
|
679 |
+
def test_list_of_objects(self, class_type: str) -> None:
|
680 |
+
module: Any = import_module(class_type)
|
681 |
+
conf = OmegaConf.structured(module.ListOfObjects)
|
682 |
+
assert conf.users[0].age == 18
|
683 |
+
assert conf.users[0].name == "Joe"
|
684 |
+
|
685 |
+
conf.users.append(module.User(name="James Bond", age=7))
|
686 |
+
assert conf.users[1].name == "James Bond"
|
687 |
+
assert conf.users[1].age == 7
|
688 |
+
|
689 |
+
with pytest.raises(ValidationError):
|
690 |
+
conf.users.append("fail")
|
691 |
+
|
692 |
+
def test_promote_api(self, class_type: str) -> None:
|
693 |
+
module: Any = import_module(class_type)
|
694 |
+
conf = OmegaConf.create(module.AnyTypeConfig)
|
695 |
+
conf._promote(None)
|
696 |
+
assert conf == OmegaConf.create(module.AnyTypeConfig)
|
697 |
+
with pytest.raises(ValueError):
|
698 |
+
conf._promote(42)
|
699 |
+
assert conf == OmegaConf.create(module.AnyTypeConfig)
|
700 |
+
|
701 |
+
def test_promote_to_class(self, class_type: str) -> None:
|
702 |
+
module: Any = import_module(class_type)
|
703 |
+
|
704 |
+
conf = OmegaConf.create(module.AnyTypeConfig)
|
705 |
+
assert OmegaConf.get_type(conf) == module.AnyTypeConfig
|
706 |
+
|
707 |
+
conf._promote(module.BoolConfig)
|
708 |
+
|
709 |
+
assert OmegaConf.get_type(conf) == module.BoolConfig
|
710 |
+
assert conf.with_default is True
|
711 |
+
assert conf.null_default is None
|
712 |
+
assert OmegaConf.is_missing(conf, "mandatory_missing")
|
713 |
+
|
714 |
+
def test_promote_to_object(self, class_type: str) -> None:
|
715 |
+
module: Any = import_module(class_type)
|
716 |
+
|
717 |
+
conf = OmegaConf.create(module.AnyTypeConfig)
|
718 |
+
assert OmegaConf.get_type(conf) == module.AnyTypeConfig
|
719 |
+
|
720 |
+
conf._promote(module.BoolConfig(with_default=False))
|
721 |
+
assert OmegaConf.get_type(conf) == module.BoolConfig
|
722 |
+
assert conf.with_default is False
|
723 |
+
|
724 |
+
def test_set_key_with_with_dataclass(self, class_type: str) -> None:
|
725 |
+
module: Any = import_module(class_type)
|
726 |
+
cfg = OmegaConf.create({"foo": [1, 2]})
|
727 |
+
cfg.foo = module.ListClass()
|
728 |
+
|
729 |
+
def test_set_list_correct_type(self, class_type: str) -> None:
|
730 |
+
module: Any = import_module(class_type)
|
731 |
+
cfg = OmegaConf.structured(module.ListClass)
|
732 |
+
value = [1, 2, 3]
|
733 |
+
cfg.list = value
|
734 |
+
cfg.tuple = value
|
735 |
+
assert cfg.list == value
|
736 |
+
assert cfg.tuple == value
|
737 |
+
|
738 |
+
@pytest.mark.parametrize("value", [1, True, "str", 3.1415, ["foo", True, 1.2]]) # type: ignore
|
739 |
+
def test_assign_wrong_type_to_list(self, class_type: str, value: Any) -> None:
|
740 |
+
module: Any = import_module(class_type)
|
741 |
+
cfg = OmegaConf.structured(module.ListClass)
|
742 |
+
with pytest.raises(ValidationError):
|
743 |
+
cfg.list = value
|
744 |
+
with pytest.raises(ValidationError):
|
745 |
+
cfg.tuple = value
|
746 |
+
|
747 |
+
@pytest.mark.parametrize( # type: ignore
|
748 |
+
"value", [1, True, "str", 3.1415, ["foo", True, 1.2], {"foo": True}]
|
749 |
+
)
|
750 |
+
def test_assign_wrong_type_to_dict(self, class_type: str, value: Any) -> None:
|
751 |
+
module: Any = import_module(class_type)
|
752 |
+
cfg = OmegaConf.structured(module.ConfigWithDict2)
|
753 |
+
with pytest.raises(ValidationError):
|
754 |
+
cfg.dict1 = value
|
755 |
+
|
756 |
+
|
757 |
+
def validate_frozen_impl(conf: DictConfig) -> None:
|
758 |
+
with pytest.raises(ReadonlyConfigError):
|
759 |
+
conf.x = 20
|
760 |
+
|
761 |
+
with pytest.raises(ReadonlyConfigError):
|
762 |
+
conf.list[0] = 10
|
763 |
+
|
764 |
+
with pytest.raises(ReadonlyConfigError):
|
765 |
+
conf.user.age = 20
|
766 |
+
|
767 |
+
# merge into is rejected because it mutates a readonly object
|
768 |
+
with pytest.raises(ReadonlyConfigError):
|
769 |
+
conf.merge_with({"user": {"name": "iceman"}})
|
770 |
+
|
771 |
+
# Normal merge is allowed.
|
772 |
+
ret = OmegaConf.merge(conf, {"user": {"name": "iceman"}})
|
773 |
+
assert ret == {"user": {"name": "iceman", "age": 10}, "x": 10, "list": [1, 2, 3]}
|
774 |
+
with pytest.raises(ReadonlyConfigError):
|
775 |
+
ret.user.age = 20
|
776 |
+
|
777 |
+
|
778 |
+
def test_attr_frozen() -> None:
|
779 |
+
from tests.structured_conf.data.attr_classes import FrozenClass
|
780 |
+
|
781 |
+
validate_frozen_impl(OmegaConf.structured(FrozenClass))
|
782 |
+
validate_frozen_impl(OmegaConf.structured(FrozenClass()))
|
783 |
+
|
784 |
+
|
785 |
+
def test_dataclass_frozen() -> None:
|
786 |
+
from tests.structured_conf.data.dataclasses import FrozenClass
|
787 |
+
|
788 |
+
validate_frozen_impl(OmegaConf.structured(FrozenClass))
|
789 |
+
validate_frozen_impl(OmegaConf.structured(FrozenClass()))
|
790 |
+
|
791 |
+
|
792 |
+
@pytest.mark.parametrize(
|
793 |
+
"class_type",
|
794 |
+
[
|
795 |
+
"tests.structured_conf.data.dataclasses",
|
796 |
+
"tests.structured_conf.data.attr_classes",
|
797 |
+
],
|
798 |
+
)
|
799 |
+
class TestDictSubclass:
|
800 |
+
def test_str2str(self, class_type: str) -> None:
|
801 |
+
module: Any = import_module(class_type)
|
802 |
+
cfg = OmegaConf.structured(module.DictSubclass.Str2Str())
|
803 |
+
cfg.hello = "world"
|
804 |
+
assert cfg.hello == "world"
|
805 |
+
|
806 |
+
with pytest.raises(KeyValidationError):
|
807 |
+
cfg[Color.RED] = "fail"
|
808 |
+
|
809 |
+
def test_str2str_as_sub_node(self, class_type: str) -> None:
|
810 |
+
module: Any = import_module(class_type)
|
811 |
+
cfg = OmegaConf.create({"foo": module.DictSubclass.Str2Str})
|
812 |
+
assert OmegaConf.get_type(cfg.foo) == module.DictSubclass.Str2Str
|
813 |
+
assert _utils.get_ref_type(cfg.foo) == Optional[module.DictSubclass.Str2Str]
|
814 |
+
|
815 |
+
cfg.foo.hello = "world"
|
816 |
+
assert cfg.foo.hello == "world"
|
817 |
+
|
818 |
+
with pytest.raises(KeyValidationError):
|
819 |
+
cfg.foo[Color.RED] = "fail"
|
820 |
+
|
821 |
+
def test_color2str(self, class_type: str) -> None:
|
822 |
+
module: Any = import_module(class_type)
|
823 |
+
cfg = OmegaConf.structured(module.DictSubclass.Color2Str())
|
824 |
+
cfg[Color.RED] = "red"
|
825 |
+
|
826 |
+
with pytest.raises(KeyValidationError):
|
827 |
+
cfg.greeen = "nope"
|
828 |
+
|
829 |
+
def test_color2color(self, class_type: str) -> None:
|
830 |
+
module: Any = import_module(class_type)
|
831 |
+
cfg = OmegaConf.structured(module.DictSubclass.Color2Color())
|
832 |
+
|
833 |
+
# add key
|
834 |
+
cfg[Color.RED] = "GREEN"
|
835 |
+
assert cfg[Color.RED] == Color.GREEN
|
836 |
+
|
837 |
+
# replace key
|
838 |
+
cfg[Color.RED] = "RED"
|
839 |
+
assert cfg[Color.RED] == Color.RED
|
840 |
+
|
841 |
+
cfg[Color.BLUE] = Color.BLUE
|
842 |
+
assert cfg[Color.BLUE] == Color.BLUE
|
843 |
+
|
844 |
+
cfg.RED = Color.RED
|
845 |
+
assert cfg.RED == Color.RED
|
846 |
+
|
847 |
+
with pytest.raises(ValidationError):
|
848 |
+
# bad value
|
849 |
+
cfg[Color.GREEN] = 10
|
850 |
+
|
851 |
+
with pytest.raises(KeyValidationError):
|
852 |
+
# bad key
|
853 |
+
cfg.greeen = "nope"
|
854 |
+
|
855 |
+
def test_str2user(self, class_type: str) -> None:
|
856 |
+
module: Any = import_module(class_type)
|
857 |
+
cfg = OmegaConf.structured(module.DictSubclass.Str2User())
|
858 |
+
|
859 |
+
cfg.bond = module.User(name="James Bond", age=7)
|
860 |
+
assert cfg.bond.name == "James Bond"
|
861 |
+
assert cfg.bond.age == 7
|
862 |
+
|
863 |
+
with pytest.raises(ValidationError):
|
864 |
+
# bad value
|
865 |
+
cfg.hello = "world"
|
866 |
+
|
867 |
+
with pytest.raises(KeyValidationError):
|
868 |
+
# bad key
|
869 |
+
cfg[Color.BLUE] = "nope"
|
870 |
+
|
871 |
+
def test_str2str_with_field(self, class_type: str) -> None:
|
872 |
+
module: Any = import_module(class_type)
|
873 |
+
cfg = OmegaConf.structured(module.DictSubclass.Str2StrWithField())
|
874 |
+
assert cfg.foo == "bar"
|
875 |
+
cfg.hello = "world"
|
876 |
+
assert cfg.hello == "world"
|
877 |
+
|
878 |
+
with pytest.raises(KeyValidationError):
|
879 |
+
cfg[Color.RED] = "fail"
|
880 |
+
|
881 |
+
def test_str2int_with_field_of_different_type(self, class_type: str) -> None:
|
882 |
+
module: Any = import_module(class_type)
|
883 |
+
cfg = OmegaConf.structured(module.DictSubclass.Str2IntWithStrField())
|
884 |
+
assert cfg.foo == "bar"
|
885 |
+
|
886 |
+
cfg.one = 1
|
887 |
+
assert cfg.one == 1
|
888 |
+
|
889 |
+
with pytest.raises(ValidationError):
|
890 |
+
# bad
|
891 |
+
cfg.hello = "world"
|
892 |
+
|
893 |
+
class TestErrors:
|
894 |
+
def test_usr2str(self, class_type: str) -> None:
|
895 |
+
module: Any = import_module(class_type)
|
896 |
+
with pytest.raises(KeyValidationError):
|
897 |
+
OmegaConf.structured(module.DictSubclass.Error.User2Str())
|
898 |
+
|
899 |
+
def test_construct_from_another_retain_node_types(self, class_type: str) -> None:
|
900 |
+
module: Any = import_module(class_type)
|
901 |
+
cfg1 = OmegaConf.create(module.User(name="James Bond", age=7))
|
902 |
+
with pytest.raises(ValidationError):
|
903 |
+
cfg1.age = "not a number"
|
904 |
+
|
905 |
+
cfg2 = OmegaConf.create(cfg1)
|
906 |
+
with pytest.raises(ValidationError):
|
907 |
+
cfg2.age = "not a number"
|
908 |
+
|
909 |
+
def test_nested_with_any_var_type(self, class_type: str) -> None:
|
910 |
+
module: Any = import_module(class_type)
|
911 |
+
cfg = OmegaConf.structured(module.NestedWithAny)
|
912 |
+
assert cfg == {
|
913 |
+
"var": {
|
914 |
+
"with_default": 10,
|
915 |
+
"null_default": None,
|
916 |
+
"mandatory_missing": "???",
|
917 |
+
"interpolation": "${value_at_root}",
|
918 |
+
}
|
919 |
+
}
|
920 |
+
|
921 |
+
def test_noop_merge_into_frozen(self, class_type: str) -> None:
|
922 |
+
module: Any = import_module(class_type)
|
923 |
+
cfg = OmegaConf.structured(module.ContainsFrozen)
|
924 |
+
ret = OmegaConf.merge(cfg, {"x": 20, "frozen": {}})
|
925 |
+
assert ret == {
|
926 |
+
"x": 20,
|
927 |
+
"frozen": {"user": {"name": "Bart", "age": 10}, "x": 10, "list": [1, 2, 3]},
|
928 |
+
}
|
929 |
+
|
930 |
+
def test_merge_into_none_list(self, class_type: str) -> None:
|
931 |
+
module: Any = import_module(class_type)
|
932 |
+
cfg = OmegaConf.structured(module.ListOptional)
|
933 |
+
assert OmegaConf.merge(cfg, {"as_none": [4, 5, 6]}) == {
|
934 |
+
"with_default": [1, 2, 3],
|
935 |
+
"as_none": [4, 5, 6],
|
936 |
+
"not_optional": [1, 2, 3],
|
937 |
+
}
|
938 |
+
|
939 |
+
assert OmegaConf.merge(cfg, cfg) == cfg
|
940 |
+
|
941 |
+
def test_merge_into_none_dict(self, class_type: str) -> None:
|
942 |
+
module: Any = import_module(class_type)
|
943 |
+
cfg = OmegaConf.structured(module.DictOptional)
|
944 |
+
assert OmegaConf.merge(cfg, {"as_none": {"x": 100}}) == {
|
945 |
+
"with_default": {"a": 10},
|
946 |
+
"as_none": {"x": 100},
|
947 |
+
"not_optional": {"a": 10},
|
948 |
+
}
|
949 |
+
|
950 |
+
assert OmegaConf.merge(cfg, cfg) == cfg
|
951 |
+
|
952 |
+
@pytest.mark.parametrize( # type: ignore
|
953 |
+
"update_value,expected",
|
954 |
+
[
|
955 |
+
pytest.param([], {"list": []}, id="empty"),
|
956 |
+
pytest.param(
|
957 |
+
[{"name": "Bond"}],
|
958 |
+
{"list": [{"name": "Bond", "age": "???"}]},
|
959 |
+
id="partial",
|
960 |
+
),
|
961 |
+
pytest.param(
|
962 |
+
[{"name": "Bond", "age": 7}],
|
963 |
+
{"list": [{"name": "Bond", "age": 7}]},
|
964 |
+
id="complete",
|
965 |
+
),
|
966 |
+
pytest.param(
|
967 |
+
[{"age": "double o seven"}],
|
968 |
+
pytest.raises(ValidationError),
|
969 |
+
id="complete",
|
970 |
+
),
|
971 |
+
],
|
972 |
+
)
|
973 |
+
def test_update_userlist(
|
974 |
+
self, class_type: str, update_value: Any, expected: Any
|
975 |
+
) -> None:
|
976 |
+
module: Any = import_module(class_type)
|
977 |
+
cfg = OmegaConf.structured(module.UserList)
|
978 |
+
if isinstance(expected, dict):
|
979 |
+
OmegaConf.update(cfg, "list", update_value, merge=True)
|
980 |
+
assert cfg == expected
|
981 |
+
else:
|
982 |
+
with pytest.raises(ValidationError):
|
983 |
+
OmegaConf.update(cfg, "list", update_value, merge=True)
|
tests/test_base_config.py
ADDED
@@ -0,0 +1,586 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
from enum import Enum
|
3 |
+
from typing import Any, Dict, List, Union
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
from pytest import raises
|
7 |
+
|
8 |
+
from omegaconf import (
|
9 |
+
Container,
|
10 |
+
DictConfig,
|
11 |
+
IntegerNode,
|
12 |
+
ListConfig,
|
13 |
+
OmegaConf,
|
14 |
+
ReadonlyConfigError,
|
15 |
+
StringNode,
|
16 |
+
ValidationError,
|
17 |
+
flag_override,
|
18 |
+
open_dict,
|
19 |
+
read_write,
|
20 |
+
)
|
21 |
+
from omegaconf.errors import ConfigKeyError
|
22 |
+
|
23 |
+
from . import Color, StructuredWithMissing, does_not_raise
|
24 |
+
|
25 |
+
|
26 |
+
@pytest.mark.parametrize( # type: ignore
|
27 |
+
"input_, key, value, expected",
|
28 |
+
[
|
29 |
+
# dict
|
30 |
+
(dict(), "foo", 10, dict(foo=10)),
|
31 |
+
(dict(), "foo", IntegerNode(10), dict(foo=10)),
|
32 |
+
(dict(foo=5), "foo", IntegerNode(10), dict(foo=10)),
|
33 |
+
# changing type of a node
|
34 |
+
(dict(foo=StringNode("str")), "foo", IntegerNode(10), dict(foo=10)),
|
35 |
+
# list
|
36 |
+
([0], 0, 10, [10]),
|
37 |
+
(["a", "b", "c"], 1, 10, ["a", 10, "c"]),
|
38 |
+
([1, 2], 1, IntegerNode(10), [1, 10]),
|
39 |
+
([1, IntegerNode(2)], 1, IntegerNode(10), [1, 10]),
|
40 |
+
# changing type of a node
|
41 |
+
([1, StringNode("str")], 1, IntegerNode(10), [1, 10]),
|
42 |
+
],
|
43 |
+
)
|
44 |
+
def test_set_value(
|
45 |
+
input_: Any, key: Union[str, int], value: Any, expected: Any
|
46 |
+
) -> None:
|
47 |
+
c = OmegaConf.create(input_)
|
48 |
+
c[key] = value
|
49 |
+
assert c == expected
|
50 |
+
|
51 |
+
|
52 |
+
@pytest.mark.parametrize( # type: ignore
|
53 |
+
"input_, key, value",
|
54 |
+
[
|
55 |
+
# dict
|
56 |
+
({"foo": IntegerNode(10)}, "foo", "str"),
|
57 |
+
# list
|
58 |
+
([1, IntegerNode(10)], 1, "str"),
|
59 |
+
],
|
60 |
+
)
|
61 |
+
def test_set_value_validation_fail(input_: Any, key: Any, value: Any) -> None:
|
62 |
+
c = OmegaConf.create(input_)
|
63 |
+
with raises(ValidationError):
|
64 |
+
c[key] = value
|
65 |
+
|
66 |
+
|
67 |
+
@pytest.mark.parametrize( # type: ignore
|
68 |
+
"input_, key, value",
|
69 |
+
[
|
70 |
+
# dict
|
71 |
+
(dict(foo=IntegerNode(10)), "foo", StringNode("str")),
|
72 |
+
# list
|
73 |
+
([1, IntegerNode(10)], 1, StringNode("str")),
|
74 |
+
],
|
75 |
+
)
|
76 |
+
def test_replace_value_node_type_with_another(
|
77 |
+
input_: Any, key: Any, value: Any
|
78 |
+
) -> None:
|
79 |
+
c = OmegaConf.create(input_)
|
80 |
+
c[key] = value
|
81 |
+
assert c[key] == value
|
82 |
+
assert c[key] == value._value()
|
83 |
+
|
84 |
+
|
85 |
+
@pytest.mark.parametrize( # type: ignore
|
86 |
+
"input_",
|
87 |
+
[
|
88 |
+
pytest.param([1, 2, 3], id="list"),
|
89 |
+
pytest.param([1, 2, {"a": 3}], id="dict_in_list"),
|
90 |
+
pytest.param([1, 2, [10, 20]], id="list_in_list"),
|
91 |
+
pytest.param({"b": {"b": 10}}, id="dict_in_dict"),
|
92 |
+
pytest.param({"b": [False, 1, "2", 3.0, Color.RED]}, id="list_in_dict"),
|
93 |
+
pytest.param({"b": DictConfig(content=None)}, id="none_dictconfig"),
|
94 |
+
pytest.param({"b": ListConfig(content=None)}, id="none_listconfig"),
|
95 |
+
pytest.param({"b": DictConfig(content="???")}, id="missing_dictconfig"),
|
96 |
+
pytest.param({"b": ListConfig(content="???")}, id="missing_listconfig"),
|
97 |
+
],
|
98 |
+
)
|
99 |
+
def test_to_container_returns_primitives(input_: Any) -> None:
|
100 |
+
def assert_container_with_primitives(item: Any) -> None:
|
101 |
+
if isinstance(item, list):
|
102 |
+
for v in item:
|
103 |
+
assert_container_with_primitives(v)
|
104 |
+
elif isinstance(item, dict):
|
105 |
+
for _k, v in item.items():
|
106 |
+
assert_container_with_primitives(v)
|
107 |
+
else:
|
108 |
+
assert isinstance(item, (int, float, str, bool, type(None), Enum))
|
109 |
+
|
110 |
+
c = OmegaConf.create(input_)
|
111 |
+
res = OmegaConf.to_container(c, resolve=True)
|
112 |
+
assert_container_with_primitives(res)
|
113 |
+
|
114 |
+
|
115 |
+
@pytest.mark.parametrize( # type: ignore
|
116 |
+
"src, expected, expected_with_resolve",
|
117 |
+
[
|
118 |
+
pytest.param([], None, None, id="empty_list"),
|
119 |
+
pytest.param([1, 2, 3], None, None, id="list"),
|
120 |
+
pytest.param([None], None, None, id="list_with_none"),
|
121 |
+
pytest.param([1, "${0}", 3], None, [1, 1, 3], id="list_with_inter"),
|
122 |
+
pytest.param({}, None, None, id="empty_dict"),
|
123 |
+
pytest.param({"foo": "bar"}, None, None, id="dict"),
|
124 |
+
pytest.param(
|
125 |
+
{"foo": "${bar}", "bar": "zonk"},
|
126 |
+
None,
|
127 |
+
{"foo": "zonk", "bar": "zonk"},
|
128 |
+
id="dict_with_inter",
|
129 |
+
),
|
130 |
+
pytest.param({"foo": None}, None, None, id="dict_with_none"),
|
131 |
+
pytest.param({"foo": "???"}, None, None, id="dict_missing_value"),
|
132 |
+
pytest.param({"foo": None}, None, None, id="dict_none_value"),
|
133 |
+
# containers
|
134 |
+
pytest.param(
|
135 |
+
{"foo": DictConfig(is_optional=True, content=None)},
|
136 |
+
{"foo": None},
|
137 |
+
None,
|
138 |
+
id="dict_none_dictconfig",
|
139 |
+
),
|
140 |
+
pytest.param(
|
141 |
+
{"foo": DictConfig(content="???")},
|
142 |
+
{"foo": "???"},
|
143 |
+
None,
|
144 |
+
id="dict_missing_dictconfig",
|
145 |
+
),
|
146 |
+
pytest.param(
|
147 |
+
{"foo": DictConfig(content="${bar}"), "bar": 10},
|
148 |
+
{"foo": "${bar}", "bar": 10},
|
149 |
+
{"foo": 10, "bar": 10},
|
150 |
+
id="dict_inter_dictconfig",
|
151 |
+
),
|
152 |
+
pytest.param(
|
153 |
+
{"foo": ListConfig(content="???")},
|
154 |
+
{"foo": "???"},
|
155 |
+
None,
|
156 |
+
id="dict_missing_listconfig",
|
157 |
+
),
|
158 |
+
pytest.param(
|
159 |
+
{"foo": ListConfig(is_optional=True, content=None)},
|
160 |
+
{"foo": None},
|
161 |
+
None,
|
162 |
+
id="dict_none_listconfig",
|
163 |
+
),
|
164 |
+
pytest.param(
|
165 |
+
{"foo": ListConfig(content="${bar}"), "bar": 10},
|
166 |
+
{"foo": "${bar}", "bar": 10},
|
167 |
+
{"foo": 10, "bar": 10},
|
168 |
+
id="dict_inter_listconfig",
|
169 |
+
),
|
170 |
+
],
|
171 |
+
)
|
172 |
+
def test_to_container(src: Any, expected: Any, expected_with_resolve: Any) -> None:
|
173 |
+
if expected is None:
|
174 |
+
expected = src
|
175 |
+
if expected_with_resolve is None:
|
176 |
+
expected_with_resolve = expected
|
177 |
+
cfg = OmegaConf.create(src)
|
178 |
+
container = OmegaConf.to_container(cfg)
|
179 |
+
assert container == expected
|
180 |
+
container = OmegaConf.to_container(cfg, resolve=True)
|
181 |
+
assert container == expected_with_resolve
|
182 |
+
|
183 |
+
|
184 |
+
def test_string_interpolation_with_readonly_parent() -> None:
|
185 |
+
cfg = OmegaConf.create({"a": 10, "b": {"c": "hello_${a}"}})
|
186 |
+
OmegaConf.set_readonly(cfg, True)
|
187 |
+
assert OmegaConf.to_container(cfg, resolve=True) == {
|
188 |
+
"a": 10,
|
189 |
+
"b": {"c": "hello_10"},
|
190 |
+
}
|
191 |
+
|
192 |
+
|
193 |
+
@pytest.mark.parametrize( # type: ignore
|
194 |
+
"src,expected",
|
195 |
+
[
|
196 |
+
pytest.param(DictConfig(content="${bar}"), "${bar}", id="DictConfig"),
|
197 |
+
pytest.param(
|
198 |
+
OmegaConf.create({"foo": DictConfig(content="${bar}")}),
|
199 |
+
{"foo": "${bar}"},
|
200 |
+
id="nested_DictConfig",
|
201 |
+
),
|
202 |
+
],
|
203 |
+
)
|
204 |
+
def test_to_container_missing_inter_no_resolve(src: Any, expected: Any) -> None:
|
205 |
+
res = OmegaConf.to_container(src, resolve=False)
|
206 |
+
assert res == expected
|
207 |
+
|
208 |
+
|
209 |
+
@pytest.mark.parametrize( # type: ignore
|
210 |
+
"input_, is_empty", [([], True), ({}, True), ([1, 2], False), (dict(a=10), False)]
|
211 |
+
)
|
212 |
+
def test_empty(input_: Any, is_empty: bool) -> None:
|
213 |
+
c = OmegaConf.create(input_)
|
214 |
+
assert c.is_empty() == is_empty
|
215 |
+
|
216 |
+
|
217 |
+
@pytest.mark.parametrize("func", [str, repr]) # type: ignore
|
218 |
+
@pytest.mark.parametrize( # type: ignore
|
219 |
+
"input_, expected",
|
220 |
+
[
|
221 |
+
pytest.param([], "[]", id="list"),
|
222 |
+
pytest.param({}, "{}", id="dict"),
|
223 |
+
pytest.param([1, 2, 3], "[1, 2, 3]", id="list"),
|
224 |
+
pytest.param([1, 2, {"a": 3}], "[1, 2, {'a': 3}]", id="dict_in_list"),
|
225 |
+
pytest.param([1, 2, [10, 20]], "[1, 2, [10, 20]]", id="list_in_list"),
|
226 |
+
pytest.param({"b": {"b": 10}}, "{'b': {'b': 10}}", id="dict"),
|
227 |
+
pytest.param({"b": [1, 2, 3]}, "{'b': [1, 2, 3]}", id="list_in_dict"),
|
228 |
+
pytest.param(
|
229 |
+
StructuredWithMissing,
|
230 |
+
(
|
231 |
+
"{'num': '???', 'opt_num': '???', 'dict': '???', 'opt_dict': '???', 'list': "
|
232 |
+
"'???', 'opt_list': '???', 'user': '???', 'opt_user': '???', 'inter_num': "
|
233 |
+
"'${num}', 'inter_user': '${user}', 'inter_opt_user': '${opt_user}'}"
|
234 |
+
),
|
235 |
+
id="structured_with_missing",
|
236 |
+
),
|
237 |
+
],
|
238 |
+
)
|
239 |
+
def test_str(func: Any, input_: Any, expected: str) -> None:
|
240 |
+
c = OmegaConf.create(input_)
|
241 |
+
string = func(c)
|
242 |
+
assert string == expected
|
243 |
+
|
244 |
+
|
245 |
+
@pytest.mark.parametrize("flag", ["readonly", "struct"]) # type: ignore
|
246 |
+
def test_flag_dict(flag: str) -> None:
|
247 |
+
c = OmegaConf.create()
|
248 |
+
assert c._get_flag(flag) is None
|
249 |
+
c._set_flag(flag, True)
|
250 |
+
assert c._get_flag(flag) is True
|
251 |
+
c._set_flag(flag, False)
|
252 |
+
assert not c._get_flag(flag) is True
|
253 |
+
c._set_flag(flag, None)
|
254 |
+
assert c._get_flag(flag) is None
|
255 |
+
|
256 |
+
|
257 |
+
@pytest.mark.parametrize("flag", ["readonly", "struct"]) # type: ignore
|
258 |
+
def test_freeze_nested_dict(flag: str) -> None:
|
259 |
+
c = OmegaConf.create(dict(a=dict(b=2)))
|
260 |
+
assert not c._get_flag(flag)
|
261 |
+
assert not c.a._get_flag(flag)
|
262 |
+
c._set_flag(flag, True)
|
263 |
+
assert c._get_flag(flag)
|
264 |
+
assert c.a._get_flag(flag)
|
265 |
+
c._set_flag(flag, False)
|
266 |
+
assert not c._get_flag(flag)
|
267 |
+
assert not c.a._get_flag(flag)
|
268 |
+
c._set_flag(flag, None)
|
269 |
+
assert not c._get_flag(flag)
|
270 |
+
assert not c.a._get_flag(flag)
|
271 |
+
c.a._set_flag(flag, True)
|
272 |
+
assert not c._get_flag(flag)
|
273 |
+
assert c.a._get_flag(flag)
|
274 |
+
|
275 |
+
|
276 |
+
@pytest.mark.parametrize(
|
277 |
+
"src", [[], [1, 2, 3], dict(), dict(a=10), StructuredWithMissing]
|
278 |
+
)
|
279 |
+
class TestDeepCopy:
|
280 |
+
def test_deepcopy(self, src: Any) -> None:
|
281 |
+
c1 = OmegaConf.create(src)
|
282 |
+
c2 = copy.deepcopy(c1)
|
283 |
+
assert c1 == c2
|
284 |
+
|
285 |
+
assert c1.__dict__.keys() == c2.__dict__.keys()
|
286 |
+
for k in c1.__dict__.keys():
|
287 |
+
assert c1.__dict__[k] == c2.__dict__[k]
|
288 |
+
|
289 |
+
assert id(c1) != id(c2)
|
290 |
+
|
291 |
+
if isinstance(c2, ListConfig):
|
292 |
+
c2.append(1000)
|
293 |
+
elif isinstance(c2, DictConfig):
|
294 |
+
c2.num = 42
|
295 |
+
assert c1 != c2
|
296 |
+
|
297 |
+
def test_deepcopy_readonly(self, src: Any) -> None:
|
298 |
+
c1 = OmegaConf.create(src)
|
299 |
+
OmegaConf.set_readonly(c1, True)
|
300 |
+
c2 = copy.deepcopy(c1)
|
301 |
+
assert c1 == c2
|
302 |
+
if isinstance(c2, ListConfig):
|
303 |
+
with raises(ReadonlyConfigError):
|
304 |
+
c2.append(1000)
|
305 |
+
elif isinstance(c2, DictConfig):
|
306 |
+
with raises(ReadonlyConfigError):
|
307 |
+
c2.num = 42
|
308 |
+
assert c1 == c2
|
309 |
+
|
310 |
+
def test_deepcopy_struct(self, src: Any) -> None:
|
311 |
+
c1 = OmegaConf.create(src)
|
312 |
+
OmegaConf.set_struct(c1, True)
|
313 |
+
c2 = copy.deepcopy(c1)
|
314 |
+
assert c1 == c2
|
315 |
+
if isinstance(c2, ListConfig):
|
316 |
+
c2.append(1000)
|
317 |
+
elif isinstance(c2, DictConfig):
|
318 |
+
with raises(AttributeError):
|
319 |
+
c2.foo = 42
|
320 |
+
|
321 |
+
|
322 |
+
def test_deepcopy_after_del() -> None:
|
323 |
+
# make sure that deepcopy does not resurrect deleted fields (as it once did, believe it or not).
|
324 |
+
c1 = OmegaConf.create(dict(foo=[1, 2, 3], bar=10))
|
325 |
+
c2 = copy.deepcopy(c1)
|
326 |
+
assert c1 == c2
|
327 |
+
del c1["foo"]
|
328 |
+
c3 = copy.deepcopy(c1)
|
329 |
+
assert c1 == c3
|
330 |
+
|
331 |
+
|
332 |
+
def test_deepcopy_after_pop() -> None:
|
333 |
+
c1 = OmegaConf.create(dict(foo=[1, 2, 3], bar=10))
|
334 |
+
c2 = copy.deepcopy(c1)
|
335 |
+
assert c1 == c2
|
336 |
+
c2.pop("foo")
|
337 |
+
assert "foo" not in c2
|
338 |
+
assert "foo" in c1
|
339 |
+
c3 = copy.deepcopy(c1)
|
340 |
+
assert "foo" in c3
|
341 |
+
|
342 |
+
|
343 |
+
def test_deepcopy_with_interpolation() -> None:
|
344 |
+
c1 = OmegaConf.create(dict(a=dict(b="${c}"), c=10))
|
345 |
+
assert c1.a.b == 10
|
346 |
+
c2 = copy.deepcopy(c1)
|
347 |
+
assert c2.a.b == 10
|
348 |
+
|
349 |
+
|
350 |
+
# Yes, there was a bug that was a combination of an interaction between the three
|
351 |
+
def test_deepcopy_and_merge_and_flags() -> None:
|
352 |
+
c1 = OmegaConf.create(
|
353 |
+
{"dataset": {"name": "imagenet", "path": "/datasets/imagenet"}, "defaults": []}
|
354 |
+
)
|
355 |
+
OmegaConf.set_struct(c1, True)
|
356 |
+
c2 = copy.deepcopy(c1)
|
357 |
+
with raises(ConfigKeyError):
|
358 |
+
OmegaConf.merge(c2, OmegaConf.from_dotlist(["dataset.bad_key=yes"]))
|
359 |
+
|
360 |
+
|
361 |
+
@pytest.mark.parametrize( # type: ignore
|
362 |
+
"cfg", [ListConfig(element_type=int, content=[]), DictConfig(content={})]
|
363 |
+
)
|
364 |
+
def test_deepcopy_preserves_container_type(cfg: Container) -> None:
|
365 |
+
cp: Container = copy.deepcopy(cfg)
|
366 |
+
assert cp._metadata.element_type == cfg._metadata.element_type
|
367 |
+
|
368 |
+
|
369 |
+
@pytest.mark.parametrize( # type: ignore
|
370 |
+
"src, flag_name, func, expectation",
|
371 |
+
[
|
372 |
+
pytest.param(
|
373 |
+
{},
|
374 |
+
"struct",
|
375 |
+
lambda c: c.__setitem__("foo", 1),
|
376 |
+
raises(KeyError),
|
377 |
+
id="struct_setiitem",
|
378 |
+
),
|
379 |
+
pytest.param(
|
380 |
+
{},
|
381 |
+
"struct",
|
382 |
+
lambda c: c.__setattr__("foo", 1),
|
383 |
+
raises(AttributeError),
|
384 |
+
id="struct_setattr",
|
385 |
+
),
|
386 |
+
pytest.param(
|
387 |
+
{},
|
388 |
+
"readonly",
|
389 |
+
lambda c: c.__setitem__("foo", 1),
|
390 |
+
raises(ReadonlyConfigError),
|
391 |
+
id="readonly",
|
392 |
+
),
|
393 |
+
],
|
394 |
+
)
|
395 |
+
def test_flag_override(
|
396 |
+
src: Dict[str, Any], flag_name: str, func: Any, expectation: Any
|
397 |
+
) -> None:
|
398 |
+
c = OmegaConf.create(src)
|
399 |
+
c._set_flag(flag_name, True)
|
400 |
+
with expectation:
|
401 |
+
func(c)
|
402 |
+
|
403 |
+
with does_not_raise():
|
404 |
+
with flag_override(c, flag_name, False):
|
405 |
+
func(c)
|
406 |
+
|
407 |
+
|
408 |
+
@pytest.mark.parametrize( # type: ignore
|
409 |
+
"src, func, expectation",
|
410 |
+
[
|
411 |
+
({}, lambda c: c.__setitem__("foo", 1), raises(ReadonlyConfigError)),
|
412 |
+
([], lambda c: c.append(1), raises(ReadonlyConfigError)),
|
413 |
+
],
|
414 |
+
)
|
415 |
+
def test_read_write_override(src: Any, func: Any, expectation: Any) -> None:
|
416 |
+
c = OmegaConf.create(src)
|
417 |
+
OmegaConf.set_readonly(c, True)
|
418 |
+
|
419 |
+
with expectation:
|
420 |
+
func(c)
|
421 |
+
|
422 |
+
with does_not_raise():
|
423 |
+
with read_write(c):
|
424 |
+
func(c)
|
425 |
+
|
426 |
+
|
427 |
+
@pytest.mark.parametrize( # type: ignore
|
428 |
+
"string, tokenized",
|
429 |
+
[
|
430 |
+
("dog,cat", ["dog", "cat"]),
|
431 |
+
("dog\\,cat\\ ", ["dog,cat "]),
|
432 |
+
("dog,\\ cat", ["dog", " cat"]),
|
433 |
+
("\\ ,cat", [" ", "cat"]),
|
434 |
+
("dog, cat", ["dog", "cat"]),
|
435 |
+
("dog, ca t", ["dog", "ca t"]),
|
436 |
+
("dog, cat", ["dog", "cat"]),
|
437 |
+
("whitespace\\ , before comma", ["whitespace ", "before comma"]),
|
438 |
+
(None, []),
|
439 |
+
("", []),
|
440 |
+
("no , escape", ["no", "escape"]),
|
441 |
+
],
|
442 |
+
)
|
443 |
+
def test_tokenize_with_escapes(string: str, tokenized: List[str]) -> None:
|
444 |
+
assert OmegaConf._tokenize_args(string) == tokenized
|
445 |
+
|
446 |
+
|
447 |
+
@pytest.mark.parametrize( # type: ignore
|
448 |
+
"src, func, expectation",
|
449 |
+
[({}, lambda c: c.__setattr__("foo", 1), raises(AttributeError))],
|
450 |
+
)
|
451 |
+
def test_struct_override(src: Any, func: Any, expectation: Any) -> None:
|
452 |
+
c = OmegaConf.create(src)
|
453 |
+
OmegaConf.set_struct(c, True)
|
454 |
+
|
455 |
+
with expectation:
|
456 |
+
func(c)
|
457 |
+
|
458 |
+
with does_not_raise():
|
459 |
+
with open_dict(c):
|
460 |
+
func(c)
|
461 |
+
|
462 |
+
|
463 |
+
@pytest.mark.parametrize( # type: ignore
|
464 |
+
"flag_name,ctx", [("struct", open_dict), ("readonly", read_write)]
|
465 |
+
)
|
466 |
+
def test_open_dict_restore(flag_name: str, ctx: Any) -> None:
|
467 |
+
"""
|
468 |
+
Tests that internal flags are restored properly when applying context on a child node
|
469 |
+
"""
|
470 |
+
cfg = OmegaConf.create({"foo": {"bar": 10}})
|
471 |
+
cfg._set_flag(flag_name, True)
|
472 |
+
assert cfg._get_node_flag(flag_name)
|
473 |
+
assert not cfg.foo._get_node_flag(flag_name)
|
474 |
+
with ctx(cfg.foo):
|
475 |
+
cfg.foo.bar = 20
|
476 |
+
assert cfg._get_node_flag(flag_name)
|
477 |
+
assert not cfg.foo._get_node_flag(flag_name)
|
478 |
+
|
479 |
+
|
480 |
+
@pytest.mark.parametrize("copy_method", [lambda x: copy.copy(x), lambda x: x.copy()])
|
481 |
+
class TestCopy:
|
482 |
+
@pytest.mark.parametrize( # type: ignore
|
483 |
+
"src", [[], [1, 2], ["a", "b", "c"], {}, {"a": "b"}, {"a": {"b": []}}]
|
484 |
+
)
|
485 |
+
def test_copy(self, copy_method: Any, src: Any) -> None:
|
486 |
+
src = OmegaConf.create(src)
|
487 |
+
cp = copy_method(src)
|
488 |
+
assert id(src) != id(cp)
|
489 |
+
assert src == cp
|
490 |
+
|
491 |
+
@pytest.mark.parametrize( # type: ignore
|
492 |
+
"src,interpolating_key,interpolated_key",
|
493 |
+
[([1, 2, "${0}"], 2, 0), ({"a": 10, "b": "${a}"}, "b", "a")],
|
494 |
+
)
|
495 |
+
def test_copy_with_interpolation(
|
496 |
+
self, copy_method: Any, src: Any, interpolating_key: str, interpolated_key: str
|
497 |
+
) -> None:
|
498 |
+
cfg = OmegaConf.create(src)
|
499 |
+
assert cfg[interpolated_key] == cfg[interpolating_key]
|
500 |
+
cp = copy_method(cfg)
|
501 |
+
assert id(cfg) != id(cp)
|
502 |
+
assert cp[interpolated_key] == cp[interpolating_key]
|
503 |
+
assert cfg[interpolated_key] == cp[interpolating_key]
|
504 |
+
|
505 |
+
# Interpolation is preserved in original
|
506 |
+
cfg[interpolated_key] = "XXX"
|
507 |
+
assert cfg[interpolated_key] == cfg[interpolating_key]
|
508 |
+
|
509 |
+
# Test interpolation is preserved in copy
|
510 |
+
cp[interpolated_key] = "XXX"
|
511 |
+
assert cp[interpolated_key] == cp[interpolating_key]
|
512 |
+
|
513 |
+
def test_list_copy_is_shallow(self, copy_method: Any) -> None:
|
514 |
+
cfg = OmegaConf.create([[10, 20]])
|
515 |
+
cp = copy_method(cfg)
|
516 |
+
assert id(cfg) != id(cp)
|
517 |
+
assert id(cfg[0]) == id(cp[0])
|
518 |
+
|
519 |
+
|
520 |
+
def test_not_implemented() -> None:
|
521 |
+
with raises(NotImplementedError):
|
522 |
+
OmegaConf()
|
523 |
+
|
524 |
+
|
525 |
+
@pytest.mark.parametrize( # type: ignore
|
526 |
+
"query, result",
|
527 |
+
[
|
528 |
+
("a", "a"),
|
529 |
+
("${foo}", 10),
|
530 |
+
("${bar}", 10),
|
531 |
+
("foo_${foo}", "foo_10"),
|
532 |
+
("foo_${bar}", "foo_10"),
|
533 |
+
],
|
534 |
+
)
|
535 |
+
def test_resolve_str_interpolation(query: str, result: Any) -> None:
|
536 |
+
cfg = OmegaConf.create({"foo": 10, "bar": "${foo}"})
|
537 |
+
assert (
|
538 |
+
cfg._resolve_interpolation(
|
539 |
+
key=None,
|
540 |
+
value=StringNode(value=query),
|
541 |
+
throw_on_missing=False,
|
542 |
+
throw_on_resolution_failure=True,
|
543 |
+
)
|
544 |
+
== result
|
545 |
+
)
|
546 |
+
|
547 |
+
|
548 |
+
def test_omegaconf_create() -> None:
|
549 |
+
assert OmegaConf.create([]) == []
|
550 |
+
assert OmegaConf.create({}) == {}
|
551 |
+
with raises(ValidationError):
|
552 |
+
assert OmegaConf.create(10) # type: ignore
|
553 |
+
|
554 |
+
|
555 |
+
@pytest.mark.parametrize( # type: ignore
|
556 |
+
"parent, key, value, expected",
|
557 |
+
[
|
558 |
+
([10, 11], 0, ["a", "b"], [["a", "b"], 11]),
|
559 |
+
([None], 0, {"foo": "bar"}, [{"foo": "bar"}]),
|
560 |
+
([None], 0, OmegaConf.create({"foo": "bar"}), [{"foo": "bar"}]),
|
561 |
+
({}, "foo", ["a", "b"], {"foo": ["a", "b"]}),
|
562 |
+
({}, "foo", ("a", "b"), {"foo": ["a", "b"]}),
|
563 |
+
({}, "foo", OmegaConf.create({"foo": "bar"}), {"foo": {"foo": "bar"}}),
|
564 |
+
],
|
565 |
+
)
|
566 |
+
def test_assign(parent: Any, key: Union[str, int], value: Any, expected: Any) -> None:
|
567 |
+
c = OmegaConf.create(parent)
|
568 |
+
c[key] = value
|
569 |
+
assert c == expected
|
570 |
+
|
571 |
+
|
572 |
+
@pytest.mark.parametrize( # type: ignore
|
573 |
+
"cfg, key, expected",
|
574 |
+
[
|
575 |
+
# dict
|
576 |
+
(OmegaConf.create({"foo": "bar"}), "foo", "bar"),
|
577 |
+
(OmegaConf.create({"foo": None}), "foo", None),
|
578 |
+
(OmegaConf.create({"foo": "???"}), "foo", "???"),
|
579 |
+
# list
|
580 |
+
(OmegaConf.create([10, 20, 30]), 1, 20),
|
581 |
+
(OmegaConf.create([10, None, 30]), 1, None),
|
582 |
+
(OmegaConf.create([10, "???", 30]), 1, "???"),
|
583 |
+
],
|
584 |
+
)
|
585 |
+
def test_get_node(cfg: Any, key: Any, expected: Any) -> None:
|
586 |
+
assert cfg._get_node(key) == expected
|
tests/test_basic_ops_dict.py
ADDED
@@ -0,0 +1,737 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
import re
|
3 |
+
import tempfile
|
4 |
+
from typing import Any, Dict, List, Optional, Union
|
5 |
+
|
6 |
+
import pytest
|
7 |
+
|
8 |
+
from omegaconf import (
|
9 |
+
MISSING,
|
10 |
+
DictConfig,
|
11 |
+
ListConfig,
|
12 |
+
MissingMandatoryValue,
|
13 |
+
OmegaConf,
|
14 |
+
UnsupportedValueType,
|
15 |
+
ValidationError,
|
16 |
+
_utils,
|
17 |
+
open_dict,
|
18 |
+
)
|
19 |
+
from omegaconf.basecontainer import BaseContainer
|
20 |
+
from omegaconf.errors import ConfigKeyError, ConfigTypeError, KeyValidationError
|
21 |
+
|
22 |
+
from . import (
|
23 |
+
ConcretePlugin,
|
24 |
+
Enum1,
|
25 |
+
IllegalType,
|
26 |
+
Plugin,
|
27 |
+
StructuredWithMissing,
|
28 |
+
User,
|
29 |
+
does_not_raise,
|
30 |
+
)
|
31 |
+
|
32 |
+
|
33 |
+
def test_setattr_deep_value() -> None:
|
34 |
+
c = OmegaConf.create({"a": {"b": {"c": 1}}})
|
35 |
+
c.a.b = 9
|
36 |
+
assert {"a": {"b": 9}} == c
|
37 |
+
|
38 |
+
|
39 |
+
def test_setattr_deep_from_empty() -> None:
|
40 |
+
c = OmegaConf.create()
|
41 |
+
# Unfortunately we can't just do c.a.b = 9 here.
|
42 |
+
# The reason is that if c.a is being accessed first and it does not exist, so there
|
43 |
+
# is nothing to call .b = 9 on.
|
44 |
+
# The alternative is to auto-create fields as they are being accessed, but this is opening
|
45 |
+
# a whole new can of worms, and is also breaking map semantics.
|
46 |
+
c.a = {}
|
47 |
+
c.a.b = 9 # type: ignore
|
48 |
+
assert {"a": {"b": 9}} == c
|
49 |
+
|
50 |
+
|
51 |
+
def test_setattr_deep_map() -> None:
|
52 |
+
c = OmegaConf.create(dict(a=dict(b=dict(c=1))))
|
53 |
+
c.a.b = {"z": 10}
|
54 |
+
assert {"a": {"b": {"z": 10}}} == c
|
55 |
+
|
56 |
+
|
57 |
+
def test_getattr() -> None:
|
58 |
+
c = OmegaConf.create("a: b")
|
59 |
+
assert isinstance(c, DictConfig)
|
60 |
+
assert "b" == c.a
|
61 |
+
|
62 |
+
|
63 |
+
def test_getattr_dict() -> None:
|
64 |
+
c = OmegaConf.create("a: {b: 1}")
|
65 |
+
assert isinstance(c, DictConfig)
|
66 |
+
assert {"b": 1} == c.a
|
67 |
+
|
68 |
+
|
69 |
+
def test_mandatory_value() -> None:
|
70 |
+
c = OmegaConf.create({"a": "???"})
|
71 |
+
with pytest.raises(MissingMandatoryValue, match="a"):
|
72 |
+
c.a
|
73 |
+
|
74 |
+
|
75 |
+
def test_nested_dict_mandatory_value() -> None:
|
76 |
+
c = OmegaConf.create(dict(a=dict(b="???")))
|
77 |
+
with pytest.raises(MissingMandatoryValue):
|
78 |
+
c.a.b
|
79 |
+
|
80 |
+
|
81 |
+
def test_subscript_get() -> None:
|
82 |
+
c = OmegaConf.create("a: b")
|
83 |
+
assert isinstance(c, DictConfig)
|
84 |
+
assert "b" == c["a"]
|
85 |
+
|
86 |
+
|
87 |
+
def test_subscript_set() -> None:
|
88 |
+
c = OmegaConf.create()
|
89 |
+
c["a"] = "b"
|
90 |
+
assert {"a": "b"} == c
|
91 |
+
|
92 |
+
|
93 |
+
def test_default_value() -> None:
|
94 |
+
c = OmegaConf.create()
|
95 |
+
assert c.missing_key or "a default value" == "a default value"
|
96 |
+
|
97 |
+
|
98 |
+
def test_get_default_value() -> None:
|
99 |
+
c = OmegaConf.create()
|
100 |
+
assert c.get("missing_key", "a default value") == "a default value"
|
101 |
+
|
102 |
+
|
103 |
+
def test_scientific_notation_float() -> None:
|
104 |
+
c = OmegaConf.create("a: 10e-3")
|
105 |
+
assert isinstance(c, DictConfig)
|
106 |
+
assert 10e-3 == c.a
|
107 |
+
|
108 |
+
|
109 |
+
@pytest.mark.parametrize("struct", [None, True, False]) # type: ignore
|
110 |
+
@pytest.mark.parametrize("default_val", [4, True, False, None]) # type: ignore
|
111 |
+
@pytest.mark.parametrize( # type: ignore
|
112 |
+
"d,select,key",
|
113 |
+
[
|
114 |
+
({"hello": {"a": 2}}, "", "missing"),
|
115 |
+
({"hello": {"a": 2}}, "hello", "missing"),
|
116 |
+
({"hello": "???"}, "", "hello"),
|
117 |
+
({"hello": "${foo}", "foo": "???"}, "", "hello"),
|
118 |
+
({"hello": None}, "", "hello"),
|
119 |
+
({"hello": "${foo}"}, "", "hello"),
|
120 |
+
({"hello": "${foo}", "foo": "???"}, "", "hello"),
|
121 |
+
({"hello": DictConfig(is_optional=True, content=None)}, "", "hello"),
|
122 |
+
({"hello": DictConfig(content="???")}, "", "hello"),
|
123 |
+
({"hello": DictConfig(content="${foo}")}, "", "hello"),
|
124 |
+
({"hello": ListConfig(is_optional=True, content=None)}, "", "hello"),
|
125 |
+
({"hello": ListConfig(content="???")}, "", "hello"),
|
126 |
+
],
|
127 |
+
)
|
128 |
+
def test_dict_get_with_default(
|
129 |
+
d: Any, select: Any, key: Any, default_val: Any, struct: Any
|
130 |
+
) -> None:
|
131 |
+
c = OmegaConf.create(d)
|
132 |
+
c = OmegaConf.select(c, select)
|
133 |
+
OmegaConf.set_struct(c, struct)
|
134 |
+
assert c.get(key, default_val) == default_val
|
135 |
+
|
136 |
+
|
137 |
+
def test_map_expansion() -> None:
|
138 |
+
c = OmegaConf.create("{a: 2, b: 10}")
|
139 |
+
assert isinstance(c, DictConfig)
|
140 |
+
|
141 |
+
def foo(a: int, b: int) -> int:
|
142 |
+
return a + b
|
143 |
+
|
144 |
+
assert 12 == foo(**c)
|
145 |
+
|
146 |
+
|
147 |
+
def test_items() -> None:
|
148 |
+
c = OmegaConf.create(dict(a=2, b=10))
|
149 |
+
assert sorted([("a", 2), ("b", 10)]) == sorted(list(c.items()))
|
150 |
+
|
151 |
+
items = c.items()
|
152 |
+
for x in [("a", 2), ("b", 10)]:
|
153 |
+
assert x in items
|
154 |
+
|
155 |
+
items2 = iter(c.items())
|
156 |
+
assert next(items2) == ("a", 2)
|
157 |
+
assert next(items2) == ("b", 10)
|
158 |
+
with pytest.raises(StopIteration):
|
159 |
+
next(items2)
|
160 |
+
|
161 |
+
|
162 |
+
def test_items2() -> None:
|
163 |
+
c = OmegaConf.create(dict(a=dict(v=1), b=dict(v=1)))
|
164 |
+
for k, v in c.items():
|
165 |
+
v.v = 2
|
166 |
+
|
167 |
+
assert c.a.v == 2
|
168 |
+
assert c.b.v == 2
|
169 |
+
|
170 |
+
|
171 |
+
def test_items_with_interpolation() -> None:
|
172 |
+
c = OmegaConf.create(dict(a=2, b="${a}"))
|
173 |
+
r = {}
|
174 |
+
for k, v in c.items():
|
175 |
+
r[k] = v
|
176 |
+
assert r["a"] == 2
|
177 |
+
assert r["b"] == 2
|
178 |
+
|
179 |
+
|
180 |
+
def test_dict_keys() -> None:
|
181 |
+
c = OmegaConf.create("{a: 2, b: 10}")
|
182 |
+
assert isinstance(c, DictConfig)
|
183 |
+
assert {"a": 2, "b": 10}.keys() == c.keys()
|
184 |
+
|
185 |
+
|
186 |
+
def test_pickle_get_root() -> None:
|
187 |
+
# Test that get_root() is reconstructed correctly for pickle loaded files.
|
188 |
+
with tempfile.TemporaryFile() as fp:
|
189 |
+
c1 = OmegaConf.create(dict(a=dict(a1=1, a2=2)))
|
190 |
+
|
191 |
+
c2 = OmegaConf.create(dict(b=dict(b1="${a.a1}", b2=4, bb=dict(bb1=3, bb2=4))))
|
192 |
+
c3 = OmegaConf.merge(c1, c2)
|
193 |
+
assert isinstance(c3, DictConfig)
|
194 |
+
|
195 |
+
import pickle
|
196 |
+
|
197 |
+
pickle.dump(c3, fp)
|
198 |
+
fp.flush()
|
199 |
+
fp.seek(0)
|
200 |
+
loaded_c3 = pickle.load(fp)
|
201 |
+
|
202 |
+
def test(conf: DictConfig) -> None:
|
203 |
+
assert conf._get_root() == conf
|
204 |
+
assert conf.a._get_root() == conf
|
205 |
+
assert conf.b._get_root() == conf
|
206 |
+
assert conf.b.bb._get_root() == conf
|
207 |
+
|
208 |
+
assert c3 == loaded_c3
|
209 |
+
test(c3)
|
210 |
+
test(loaded_c3)
|
211 |
+
|
212 |
+
|
213 |
+
def test_iterate_dictionary() -> None:
|
214 |
+
c = OmegaConf.create({"a": 1, "b": 2})
|
215 |
+
m2 = {}
|
216 |
+
for key in c:
|
217 |
+
m2[key] = c[key]
|
218 |
+
assert m2 == c
|
219 |
+
|
220 |
+
|
221 |
+
def test_iterate_dict_with_interpolation() -> None:
|
222 |
+
c = OmegaConf.create({"a": "${b}", "b": 2})
|
223 |
+
expected = [("a", 2), ("b", 2)]
|
224 |
+
i = 0
|
225 |
+
for k, v in c.items():
|
226 |
+
assert k == expected[i][0]
|
227 |
+
assert v == expected[i][1]
|
228 |
+
i = i + 1
|
229 |
+
|
230 |
+
|
231 |
+
@pytest.mark.parametrize( # type: ignore
|
232 |
+
"cfg, key, default_, expected",
|
233 |
+
[
|
234 |
+
pytest.param({"a": 1, "b": 2}, "a", "__NO_DEFAULT__", 1, id="no_default"),
|
235 |
+
pytest.param({"a": 1, "b": 2}, "not_found", None, None, id="none_default"),
|
236 |
+
pytest.param(
|
237 |
+
{"a": 1, "b": 2}, "not_found", "default", "default", id="with_default"
|
238 |
+
),
|
239 |
+
# Interpolations
|
240 |
+
pytest.param(
|
241 |
+
{"a": "${b}", "b": 2}, "a", "__NO_DEFAULT__", 2, id="interpolation"
|
242 |
+
),
|
243 |
+
pytest.param(
|
244 |
+
{"a": "${b}"}, "a", "default", "default", id="interpolation_with_default"
|
245 |
+
),
|
246 |
+
# enum key
|
247 |
+
pytest.param(
|
248 |
+
{Enum1.FOO: "bar"},
|
249 |
+
Enum1.FOO,
|
250 |
+
"__NO_DEFAULT__",
|
251 |
+
"bar",
|
252 |
+
id="enum_key_no_default",
|
253 |
+
),
|
254 |
+
pytest.param(
|
255 |
+
{Enum1.FOO: "bar"}, Enum1.BAR, None, None, id="enum_key_with_none_default"
|
256 |
+
),
|
257 |
+
pytest.param(
|
258 |
+
{Enum1.FOO: "bar"},
|
259 |
+
Enum1.BAR,
|
260 |
+
"default",
|
261 |
+
"default",
|
262 |
+
id="enum_key_with_default",
|
263 |
+
),
|
264 |
+
],
|
265 |
+
)
|
266 |
+
def test_dict_pop(cfg: Dict[Any, Any], key: Any, default_: Any, expected: Any) -> None:
|
267 |
+
c = OmegaConf.create(cfg)
|
268 |
+
|
269 |
+
if default_ != "__NO_DEFAULT__":
|
270 |
+
val = c.pop(key, default_)
|
271 |
+
else:
|
272 |
+
val = c.pop(key)
|
273 |
+
|
274 |
+
assert val == expected
|
275 |
+
assert type(val) == type(expected)
|
276 |
+
|
277 |
+
|
278 |
+
def test_dict_struct_mode_pop() -> None:
|
279 |
+
cfg = OmegaConf.create({"name": "Bond", "age": 7})
|
280 |
+
cfg._set_flag("struct", True)
|
281 |
+
with pytest.raises(ConfigTypeError):
|
282 |
+
cfg.pop("name")
|
283 |
+
|
284 |
+
with pytest.raises(ConfigTypeError):
|
285 |
+
cfg.pop("bar")
|
286 |
+
|
287 |
+
with pytest.raises(ConfigTypeError):
|
288 |
+
cfg.pop("bar", "not even with default")
|
289 |
+
|
290 |
+
|
291 |
+
def test_dict_structured_mode_pop() -> None:
|
292 |
+
cfg = OmegaConf.create({"user": User(name="Bond")})
|
293 |
+
with pytest.raises(ConfigTypeError):
|
294 |
+
cfg.user.pop("name")
|
295 |
+
|
296 |
+
with pytest.raises(ConfigTypeError):
|
297 |
+
cfg.user.pop("bar")
|
298 |
+
|
299 |
+
with pytest.raises(ConfigTypeError):
|
300 |
+
cfg.user.pop("bar", "not even with default")
|
301 |
+
|
302 |
+
# Unlocking the top level node is not enough.
|
303 |
+
with pytest.raises(ConfigTypeError):
|
304 |
+
with open_dict(cfg):
|
305 |
+
cfg.user.pop("name")
|
306 |
+
|
307 |
+
# You need to unlock the specified structured node to pop a field from it.
|
308 |
+
with open_dict(cfg.user):
|
309 |
+
cfg.user.pop("name")
|
310 |
+
assert "name" not in cfg.user
|
311 |
+
|
312 |
+
|
313 |
+
@pytest.mark.parametrize( # type: ignore
|
314 |
+
"cfg, key, expectation",
|
315 |
+
[
|
316 |
+
({"a": 1, "b": 2}, "not_found", pytest.raises(KeyError)),
|
317 |
+
# Interpolations
|
318 |
+
({"a": "???", "b": 2}, "a", pytest.raises(MissingMandatoryValue)),
|
319 |
+
({"a": "${b}", "b": "???"}, "a", pytest.raises(MissingMandatoryValue)),
|
320 |
+
# enum key
|
321 |
+
({Enum1.FOO: "bar"}, Enum1.BAR, pytest.raises(KeyError)),
|
322 |
+
],
|
323 |
+
)
|
324 |
+
def test_dict_pop_error(cfg: Dict[Any, Any], key: Any, expectation: Any) -> None:
|
325 |
+
c = OmegaConf.create(cfg)
|
326 |
+
with expectation:
|
327 |
+
c.pop(key)
|
328 |
+
assert c == cfg
|
329 |
+
|
330 |
+
|
331 |
+
@pytest.mark.parametrize( # type: ignore
|
332 |
+
"conf,key,expected",
|
333 |
+
[
|
334 |
+
({"a": 1, "b": {}}, "a", True),
|
335 |
+
({"a": 1, "b": {}}, "b", True),
|
336 |
+
({"a": 1, "b": {}}, "c", False),
|
337 |
+
({"a": 1, "b": "${a}"}, "b", True),
|
338 |
+
({"a": 1, "b": "???"}, "b", False),
|
339 |
+
({"a": 1, "b": "???", "c": "${b}"}, "c", False),
|
340 |
+
({"a": 1, "b": "${not_found}"}, "b", False),
|
341 |
+
({"a": "${unknown_resolver:bar}"}, "a", True),
|
342 |
+
({"a": None, "b": "${a}"}, "b", True),
|
343 |
+
({"a": "cat", "b": "${a}"}, "b", True),
|
344 |
+
({Enum1.FOO: 1, "b": {}}, Enum1.FOO, True),
|
345 |
+
],
|
346 |
+
)
|
347 |
+
def test_in_dict(conf: Any, key: str, expected: Any) -> None:
|
348 |
+
conf = OmegaConf.create(conf)
|
349 |
+
assert (key in conf) == expected
|
350 |
+
|
351 |
+
|
352 |
+
def test_get_root() -> None:
|
353 |
+
c = OmegaConf.create(dict(a=123, b=dict(bb=456, cc=7)))
|
354 |
+
assert c._get_root() == c
|
355 |
+
assert c.b._get_root() == c
|
356 |
+
|
357 |
+
|
358 |
+
def test_get_root_of_merged() -> None:
|
359 |
+
c1 = OmegaConf.create(dict(a=dict(a1=1, a2=2)))
|
360 |
+
|
361 |
+
c2 = OmegaConf.create(dict(b=dict(b1="???", b2=4, bb=dict(bb1=3, bb2=4))))
|
362 |
+
c3 = OmegaConf.merge(c1, c2)
|
363 |
+
assert isinstance(c3, DictConfig)
|
364 |
+
|
365 |
+
assert c3._get_root() == c3
|
366 |
+
assert c3.a._get_root() == c3
|
367 |
+
assert c3.b._get_root() == c3
|
368 |
+
assert c3.b.bb._get_root() == c3
|
369 |
+
|
370 |
+
|
371 |
+
def test_dict_config() -> None:
|
372 |
+
c = OmegaConf.create(dict())
|
373 |
+
assert isinstance(c, DictConfig)
|
374 |
+
|
375 |
+
|
376 |
+
def test_dict_delitem() -> None:
|
377 |
+
src = {"a": 10, "b": 11}
|
378 |
+
c = OmegaConf.create(src)
|
379 |
+
assert c == src
|
380 |
+
del c["a"]
|
381 |
+
assert c == {"b": 11}
|
382 |
+
with pytest.raises(KeyError):
|
383 |
+
del c["not_found"]
|
384 |
+
|
385 |
+
|
386 |
+
def test_dict_struct_delitem() -> None:
|
387 |
+
src = {"a": 10, "b": 11}
|
388 |
+
c = OmegaConf.create(src)
|
389 |
+
OmegaConf.set_struct(c, True)
|
390 |
+
with pytest.raises(ConfigTypeError):
|
391 |
+
del c["a"]
|
392 |
+
with open_dict(c):
|
393 |
+
del c["a"]
|
394 |
+
assert "a" not in c
|
395 |
+
|
396 |
+
|
397 |
+
def test_dict_structured_delitem() -> None:
|
398 |
+
c = OmegaConf.structured(User(name="Bond"))
|
399 |
+
with pytest.raises(ConfigTypeError):
|
400 |
+
del c["name"]
|
401 |
+
|
402 |
+
with open_dict(c):
|
403 |
+
del c["name"]
|
404 |
+
assert "name" not in c
|
405 |
+
|
406 |
+
|
407 |
+
def test_dict_nested_structured_delitem() -> None:
|
408 |
+
c = OmegaConf.create({"user": User(name="Bond")})
|
409 |
+
with pytest.raises(ConfigTypeError):
|
410 |
+
del c.user["name"]
|
411 |
+
|
412 |
+
# Unlocking the top level node is not enough.
|
413 |
+
with pytest.raises(ConfigTypeError):
|
414 |
+
with open_dict(c):
|
415 |
+
del c.user["name"]
|
416 |
+
|
417 |
+
# You need to unlock the specified structured node to delete a field from it.
|
418 |
+
with open_dict(c.user):
|
419 |
+
del c.user["name"]
|
420 |
+
assert "name" not in c.user
|
421 |
+
|
422 |
+
|
423 |
+
@pytest.mark.parametrize( # type: ignore
|
424 |
+
"d, expected", [({}, 0), ({"a": 10, "b": 11}, 2)]
|
425 |
+
)
|
426 |
+
def test_dict_len(d: Any, expected: Any) -> None:
|
427 |
+
c = OmegaConf.create(d)
|
428 |
+
assert len(c) == expected
|
429 |
+
|
430 |
+
|
431 |
+
def test_dict_assign_illegal_value() -> None:
|
432 |
+
c = OmegaConf.create()
|
433 |
+
with pytest.raises(UnsupportedValueType, match=re.escape("key: a")):
|
434 |
+
c.a = IllegalType()
|
435 |
+
|
436 |
+
|
437 |
+
def test_dict_assign_illegal_value_nested() -> None:
|
438 |
+
c = OmegaConf.create({"a": {}})
|
439 |
+
with pytest.raises(UnsupportedValueType, match=re.escape("key: a.b")):
|
440 |
+
c.a.b = IllegalType()
|
441 |
+
|
442 |
+
|
443 |
+
def test_assign_dict_in_dict() -> None:
|
444 |
+
c = OmegaConf.create({})
|
445 |
+
c.foo = {"foo": "bar"}
|
446 |
+
assert c.foo == {"foo": "bar"}
|
447 |
+
assert isinstance(c.foo, DictConfig)
|
448 |
+
|
449 |
+
|
450 |
+
def test_instantiate_config_fails() -> None:
|
451 |
+
with pytest.raises(TypeError):
|
452 |
+
BaseContainer() # type: ignore
|
453 |
+
|
454 |
+
|
455 |
+
@pytest.mark.parametrize( # type: ignore
|
456 |
+
"cfg, key, expected",
|
457 |
+
[
|
458 |
+
({"a": 1, "b": 2, "c": 3}, None, ["a", "b", "c"]),
|
459 |
+
({"a": {}}, "a", []),
|
460 |
+
(StructuredWithMissing, "dict", []),
|
461 |
+
],
|
462 |
+
)
|
463 |
+
def test_dir(cfg: Any, key: Any, expected: Any) -> None:
|
464 |
+
c = OmegaConf.create(cfg)
|
465 |
+
if key is None:
|
466 |
+
assert dir(c) == expected
|
467 |
+
else:
|
468 |
+
assert dir(c._get_node(key)) == expected
|
469 |
+
|
470 |
+
|
471 |
+
def test_hash() -> None:
|
472 |
+
c1 = OmegaConf.create(dict(a=10))
|
473 |
+
c2 = OmegaConf.create(dict(a=10))
|
474 |
+
assert hash(c1) == hash(c2)
|
475 |
+
c2.a = 20
|
476 |
+
assert hash(c1) != hash(c2)
|
477 |
+
|
478 |
+
|
479 |
+
@pytest.mark.parametrize("default", ["default", 0, None]) # type: ignore
|
480 |
+
def test_get_with_default_from_struct_not_throwing(default: Any) -> None:
|
481 |
+
c = OmegaConf.create({"a": 10, "b": 20})
|
482 |
+
OmegaConf.set_struct(c, True)
|
483 |
+
assert c.get("z", default) == default
|
484 |
+
|
485 |
+
|
486 |
+
def test_members() -> None:
|
487 |
+
# Make sure accessing __members__ does not return None or throw.
|
488 |
+
c = OmegaConf.create({"foo": {}})
|
489 |
+
with pytest.raises(AttributeError):
|
490 |
+
c.__members__
|
491 |
+
|
492 |
+
|
493 |
+
@pytest.mark.parametrize( # type: ignore
|
494 |
+
"in_cfg, mask_keys, expected",
|
495 |
+
[
|
496 |
+
({}, [], {}),
|
497 |
+
({"a": 1}, "a", {"a": 1}),
|
498 |
+
({"a": 1}, ["b"], {}),
|
499 |
+
({"a": 1, "b": 2}, "b", {"b": 2}),
|
500 |
+
({"a": 1, "b": 2}, ["a", "b"], {"a": 1, "b": 2}),
|
501 |
+
],
|
502 |
+
)
|
503 |
+
def test_masked_copy(
|
504 |
+
in_cfg: Dict[str, Any], mask_keys: Union[str, List[str]], expected: Any
|
505 |
+
) -> None:
|
506 |
+
cfg = OmegaConf.create(in_cfg)
|
507 |
+
masked = OmegaConf.masked_copy(cfg, keys=mask_keys)
|
508 |
+
assert masked == expected
|
509 |
+
|
510 |
+
|
511 |
+
def test_masked_copy_is_deep() -> None:
|
512 |
+
cfg = OmegaConf.create({"a": {"b": 1, "c": 2}})
|
513 |
+
expected = {"a": {"b": 1, "c": 2}}
|
514 |
+
masked = OmegaConf.masked_copy(cfg, keys=["a"])
|
515 |
+
assert masked == expected
|
516 |
+
cfg.a.b = 2
|
517 |
+
assert cfg != expected
|
518 |
+
|
519 |
+
with pytest.raises(ValueError):
|
520 |
+
OmegaConf.masked_copy("fail", []) # type: ignore
|
521 |
+
|
522 |
+
|
523 |
+
def test_shallow_copy() -> None:
|
524 |
+
cfg = OmegaConf.create({"a": 1, "b": 2})
|
525 |
+
c = cfg.copy()
|
526 |
+
cfg.a = 42
|
527 |
+
assert cfg.a == 42
|
528 |
+
assert c.a == 1
|
529 |
+
|
530 |
+
|
531 |
+
def test_shallow_copy_missing() -> None:
|
532 |
+
cfg = DictConfig(content=MISSING)
|
533 |
+
c = cfg.copy()
|
534 |
+
c._set_value({"foo": 1})
|
535 |
+
assert c.foo == 1
|
536 |
+
assert cfg._is_missing()
|
537 |
+
|
538 |
+
|
539 |
+
def test_shallow_copy_none() -> None:
|
540 |
+
cfg = DictConfig(content=None)
|
541 |
+
c = cfg.copy()
|
542 |
+
c._set_value({"foo": 1})
|
543 |
+
assert c.foo == 1
|
544 |
+
assert cfg._is_none()
|
545 |
+
|
546 |
+
|
547 |
+
def test_creation_with_invalid_key() -> None:
|
548 |
+
with pytest.raises(KeyValidationError):
|
549 |
+
OmegaConf.create({1: "a"}) # type: ignore
|
550 |
+
|
551 |
+
|
552 |
+
def test_set_with_invalid_key() -> None:
|
553 |
+
cfg = OmegaConf.create()
|
554 |
+
with pytest.raises(KeyValidationError):
|
555 |
+
cfg[1] = "a" # type: ignore
|
556 |
+
|
557 |
+
|
558 |
+
def test_get_with_invalid_key() -> None:
|
559 |
+
cfg = OmegaConf.create()
|
560 |
+
with pytest.raises(KeyValidationError):
|
561 |
+
cfg[1] # type: ignore
|
562 |
+
|
563 |
+
|
564 |
+
def test_hasattr() -> None:
|
565 |
+
cfg = OmegaConf.create({"foo": "bar"})
|
566 |
+
OmegaConf.set_struct(cfg, True)
|
567 |
+
assert hasattr(cfg, "foo")
|
568 |
+
assert not hasattr(cfg, "buz")
|
569 |
+
|
570 |
+
|
571 |
+
def test_struct_mode_missing_key_getitem() -> None:
|
572 |
+
cfg = OmegaConf.create({"foo": "bar"})
|
573 |
+
OmegaConf.set_struct(cfg, True)
|
574 |
+
with pytest.raises(KeyError):
|
575 |
+
cfg.__getitem__("zoo")
|
576 |
+
|
577 |
+
|
578 |
+
def test_struct_mode_missing_key_setitem() -> None:
|
579 |
+
cfg = OmegaConf.create({"foo": "bar"})
|
580 |
+
OmegaConf.set_struct(cfg, True)
|
581 |
+
with pytest.raises(KeyError):
|
582 |
+
cfg.__setitem__("zoo", 10)
|
583 |
+
|
584 |
+
|
585 |
+
def test_get_type() -> None:
|
586 |
+
|
587 |
+
cfg = OmegaConf.structured(User)
|
588 |
+
assert OmegaConf.get_type(cfg) == User
|
589 |
+
|
590 |
+
cfg = OmegaConf.structured(User(name="bond"))
|
591 |
+
assert OmegaConf.get_type(cfg) == User
|
592 |
+
|
593 |
+
cfg = OmegaConf.create({"user": User, "inter": "${user}"})
|
594 |
+
assert OmegaConf.get_type(cfg.user) == User
|
595 |
+
assert OmegaConf.get_type(cfg.inter) == User
|
596 |
+
|
597 |
+
|
598 |
+
@pytest.mark.parametrize( # type: ignore
|
599 |
+
"cfg, expected_ref_type",
|
600 |
+
[
|
601 |
+
(
|
602 |
+
OmegaConf.create(
|
603 |
+
{"plugin": DictConfig(ref_type=Plugin, content=ConcretePlugin)}
|
604 |
+
),
|
605 |
+
Optional[Plugin],
|
606 |
+
),
|
607 |
+
(
|
608 |
+
OmegaConf.create(
|
609 |
+
{
|
610 |
+
"plugin": DictConfig(
|
611 |
+
ref_type=Plugin, content=ConcretePlugin, is_optional=False
|
612 |
+
)
|
613 |
+
}
|
614 |
+
),
|
615 |
+
Plugin,
|
616 |
+
),
|
617 |
+
],
|
618 |
+
)
|
619 |
+
def test_get_ref_type(cfg: Any, expected_ref_type: Any) -> None:
|
620 |
+
assert _utils.get_ref_type(cfg.plugin) == expected_ref_type
|
621 |
+
|
622 |
+
|
623 |
+
def test_get_ref_type_with_conflict() -> None:
|
624 |
+
cfg = OmegaConf.create(
|
625 |
+
{"user": User, "inter": DictConfig(ref_type=Plugin, content="${user}")}
|
626 |
+
)
|
627 |
+
|
628 |
+
assert OmegaConf.get_type(cfg.user) == User
|
629 |
+
assert _utils.get_ref_type(cfg.user) == Optional[User]
|
630 |
+
|
631 |
+
# Interpolation inherits both type and ref type from the target
|
632 |
+
assert OmegaConf.get_type(cfg.inter) == User
|
633 |
+
assert _utils.get_ref_type(cfg.inter) == Optional[User]
|
634 |
+
|
635 |
+
|
636 |
+
def test_is_missing() -> None:
|
637 |
+
cfg = OmegaConf.create(
|
638 |
+
{
|
639 |
+
"missing_node": DictConfig(content="???"),
|
640 |
+
"foo": "???",
|
641 |
+
"inter": "${foo}",
|
642 |
+
"str_inter": "zoo_${foo}",
|
643 |
+
"missing_node_inter": "${missing_node}",
|
644 |
+
}
|
645 |
+
)
|
646 |
+
assert cfg._get_node("foo")._is_missing() # type:ignore
|
647 |
+
assert cfg._get_node("inter")._is_missing() # type:ignore
|
648 |
+
assert cfg._get_node("str_inter")._is_missing() # type:ignore
|
649 |
+
assert cfg._get_node("missing_node")._is_missing() # type:ignore
|
650 |
+
assert cfg._get_node("missing_node_inter")._is_missing() # type:ignore
|
651 |
+
|
652 |
+
|
653 |
+
@pytest.mark.parametrize("ref_type", [None, Any]) # type: ignore
|
654 |
+
@pytest.mark.parametrize("assign", [None, {}, {"foo": "bar"}, [1, 2, 3]]) # type: ignore
|
655 |
+
def test_assign_to_reftype_none_or_any(ref_type: Any, assign: Any) -> None:
|
656 |
+
cfg = OmegaConf.create({"foo": DictConfig(ref_type=ref_type, content={})})
|
657 |
+
cfg.foo = assign
|
658 |
+
assert cfg.foo == assign
|
659 |
+
|
660 |
+
|
661 |
+
@pytest.mark.parametrize( # type: ignore
|
662 |
+
"ref_type,values,assign,expectation",
|
663 |
+
[
|
664 |
+
(Plugin, [None, "???", Plugin], None, does_not_raise),
|
665 |
+
(Plugin, [None, "???", Plugin], Plugin, does_not_raise),
|
666 |
+
(Plugin, [None, "???", Plugin], Plugin(), does_not_raise),
|
667 |
+
(Plugin, [None, "???", Plugin], ConcretePlugin, does_not_raise),
|
668 |
+
(Plugin, [None, "???", Plugin], ConcretePlugin(), does_not_raise),
|
669 |
+
(Plugin, [None, "???", Plugin], 10, lambda: pytest.raises(ValidationError)),
|
670 |
+
(ConcretePlugin, [None, "???", ConcretePlugin], None, does_not_raise),
|
671 |
+
(
|
672 |
+
ConcretePlugin,
|
673 |
+
[None, "???", ConcretePlugin],
|
674 |
+
Plugin,
|
675 |
+
lambda: pytest.raises(ValidationError),
|
676 |
+
),
|
677 |
+
(
|
678 |
+
ConcretePlugin,
|
679 |
+
[None, "???", ConcretePlugin],
|
680 |
+
Plugin(),
|
681 |
+
lambda: pytest.raises(ValidationError),
|
682 |
+
),
|
683 |
+
(
|
684 |
+
ConcretePlugin,
|
685 |
+
[None, "???", ConcretePlugin],
|
686 |
+
ConcretePlugin,
|
687 |
+
does_not_raise,
|
688 |
+
),
|
689 |
+
(
|
690 |
+
ConcretePlugin,
|
691 |
+
[None, "???", ConcretePlugin],
|
692 |
+
ConcretePlugin(),
|
693 |
+
does_not_raise,
|
694 |
+
),
|
695 |
+
],
|
696 |
+
)
|
697 |
+
def test_assign_to_reftype_plugin(
|
698 |
+
ref_type: Any, values: List[Any], assign: Any, expectation: Any
|
699 |
+
) -> None:
|
700 |
+
for value in values:
|
701 |
+
cfg = OmegaConf.create({"foo": DictConfig(ref_type=ref_type, content=value)})
|
702 |
+
with expectation():
|
703 |
+
assert _utils.get_ref_type(cfg, "foo") == Optional[ref_type]
|
704 |
+
cfg.foo = assign
|
705 |
+
assert cfg.foo == assign
|
706 |
+
# validate assignment does not change ref type.
|
707 |
+
assert _utils.get_ref_type(cfg, "foo") == Optional[ref_type]
|
708 |
+
|
709 |
+
if value is not None:
|
710 |
+
cfg = OmegaConf.create(
|
711 |
+
{"foo": DictConfig(ref_type=ref_type, content=value)}
|
712 |
+
)
|
713 |
+
with expectation():
|
714 |
+
cfg2 = OmegaConf.merge(cfg, {"foo": assign})
|
715 |
+
assert isinstance(cfg2, DictConfig)
|
716 |
+
assert cfg2.foo == assign
|
717 |
+
|
718 |
+
|
719 |
+
def test_setdefault() -> None:
|
720 |
+
cfg = OmegaConf.create({})
|
721 |
+
assert cfg.setdefault("foo", 10) == 10
|
722 |
+
assert cfg["foo"] == 10
|
723 |
+
assert cfg.setdefault("foo", 20) == 10
|
724 |
+
assert cfg["foo"] == 10
|
725 |
+
|
726 |
+
cfg = OmegaConf.create({})
|
727 |
+
OmegaConf.set_struct(cfg, True)
|
728 |
+
with pytest.raises(ConfigKeyError):
|
729 |
+
assert cfg.setdefault("foo", 10) == 10
|
730 |
+
assert cfg == {}
|
731 |
+
with open_dict(cfg):
|
732 |
+
assert cfg.setdefault("foo", 10) == 10
|
733 |
+
|
734 |
+
assert cfg.setdefault("foo", 20) == 10
|
735 |
+
assert cfg["foo"] == 10
|
736 |
+
|
737 |
+
assert cfg["foo"] == 10
|
tests/test_basic_ops_list.py
ADDED
@@ -0,0 +1,591 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
import re
|
3 |
+
from typing import Any, List, Optional
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from omegaconf import AnyNode, ListConfig, OmegaConf
|
8 |
+
from omegaconf.errors import (
|
9 |
+
ConfigKeyError,
|
10 |
+
ConfigTypeError,
|
11 |
+
KeyValidationError,
|
12 |
+
MissingMandatoryValue,
|
13 |
+
UnsupportedValueType,
|
14 |
+
ValidationError,
|
15 |
+
)
|
16 |
+
from omegaconf.nodes import IntegerNode, StringNode
|
17 |
+
|
18 |
+
from . import Color, IllegalType, User, does_not_raise
|
19 |
+
|
20 |
+
|
21 |
+
def test_list_value() -> None:
|
22 |
+
c = OmegaConf.create("a: [1,2]")
|
23 |
+
assert {"a": [1, 2]} == c
|
24 |
+
|
25 |
+
|
26 |
+
def test_list_of_dicts() -> None:
|
27 |
+
v = [dict(key1="value1"), dict(key2="value2")]
|
28 |
+
c = OmegaConf.create(v)
|
29 |
+
assert c[0].key1 == "value1"
|
30 |
+
assert c[1].key2 == "value2"
|
31 |
+
|
32 |
+
|
33 |
+
def test_list_get_with_default() -> None:
|
34 |
+
c = OmegaConf.create([None, "???", "found"])
|
35 |
+
assert c.get(0, "default_value") == "default_value"
|
36 |
+
assert c.get(1, "default_value") == "default_value"
|
37 |
+
assert c.get(2, "default_value") == "found"
|
38 |
+
|
39 |
+
|
40 |
+
@pytest.mark.parametrize( # type: ignore
|
41 |
+
"input_, expected, list_key",
|
42 |
+
[
|
43 |
+
pytest.param([1, 2], [1, 2], None, id="simple"),
|
44 |
+
pytest.param(["${1}", 2], [2, 2], None, id="interpolation"),
|
45 |
+
pytest.param(
|
46 |
+
{
|
47 |
+
"defaults": [
|
48 |
+
{"optimizer": "adam"},
|
49 |
+
{"dataset": "imagenet"},
|
50 |
+
{"foo": "${defaults.0.optimizer}_${defaults.1.dataset}"},
|
51 |
+
]
|
52 |
+
},
|
53 |
+
[{"optimizer": "adam"}, {"dataset": "imagenet"}, {"foo": "adam_imagenet"}],
|
54 |
+
"defaults",
|
55 |
+
id="str_interpolation",
|
56 |
+
),
|
57 |
+
],
|
58 |
+
)
|
59 |
+
def test_iterate_list(input_: Any, expected: Any, list_key: str) -> None:
|
60 |
+
c = OmegaConf.create(input_)
|
61 |
+
if list_key is not None:
|
62 |
+
lst = c.get(list_key)
|
63 |
+
else:
|
64 |
+
lst = c
|
65 |
+
items = [x for x in lst]
|
66 |
+
assert items == expected
|
67 |
+
|
68 |
+
|
69 |
+
def test_iterate_list_with_missing_interpolation() -> None:
|
70 |
+
c = OmegaConf.create([1, "${10}"])
|
71 |
+
itr = iter(c)
|
72 |
+
assert 1 == next(itr)
|
73 |
+
with pytest.raises(ConfigKeyError):
|
74 |
+
next(itr)
|
75 |
+
|
76 |
+
|
77 |
+
def test_iterate_list_with_missing() -> None:
|
78 |
+
c = OmegaConf.create([1, "???"])
|
79 |
+
itr = iter(c)
|
80 |
+
assert 1 == next(itr)
|
81 |
+
with pytest.raises(MissingMandatoryValue):
|
82 |
+
next(itr)
|
83 |
+
|
84 |
+
|
85 |
+
def test_items_with_interpolation() -> None:
|
86 |
+
c = OmegaConf.create(["foo", "${0}"])
|
87 |
+
assert c == ["foo", "foo"]
|
88 |
+
|
89 |
+
|
90 |
+
def test_list_pop() -> None:
|
91 |
+
c = OmegaConf.create([1, 2, 3, 4])
|
92 |
+
assert c.pop(0) == 1
|
93 |
+
assert c.pop() == 4
|
94 |
+
assert c == [2, 3]
|
95 |
+
with pytest.raises(IndexError):
|
96 |
+
c.pop(100)
|
97 |
+
validate_list_keys(c)
|
98 |
+
|
99 |
+
|
100 |
+
def test_list_pop_on_unexpected_exception_not_modifying() -> None:
|
101 |
+
src = [1, 2, 3, 4]
|
102 |
+
c = OmegaConf.create(src)
|
103 |
+
|
104 |
+
with pytest.raises(ConfigTypeError):
|
105 |
+
c.pop("foo") # type: ignore
|
106 |
+
assert c == src
|
107 |
+
|
108 |
+
|
109 |
+
def test_in_list() -> None:
|
110 |
+
c = OmegaConf.create([10, 11, dict(a=12)])
|
111 |
+
assert 10 in c
|
112 |
+
assert 11 in c
|
113 |
+
assert dict(a=12) in c
|
114 |
+
assert "blah" not in c
|
115 |
+
|
116 |
+
|
117 |
+
def test_list_config_with_list() -> None:
|
118 |
+
c = OmegaConf.create([])
|
119 |
+
assert isinstance(c, ListConfig)
|
120 |
+
|
121 |
+
|
122 |
+
def test_list_config_with_tuple() -> None:
|
123 |
+
c = OmegaConf.create(())
|
124 |
+
assert isinstance(c, ListConfig)
|
125 |
+
|
126 |
+
|
127 |
+
def test_items_on_list() -> None:
|
128 |
+
c = OmegaConf.create([1, 2])
|
129 |
+
with pytest.raises(AttributeError):
|
130 |
+
c.items()
|
131 |
+
|
132 |
+
|
133 |
+
def test_list_enumerate() -> None:
|
134 |
+
src: List[Optional[str]] = ["a", "b", "c", "d"]
|
135 |
+
c = OmegaConf.create(src)
|
136 |
+
for i, v in enumerate(c):
|
137 |
+
assert src[i] == v
|
138 |
+
assert v is not None
|
139 |
+
src[i] = None
|
140 |
+
|
141 |
+
for v in src:
|
142 |
+
assert v is None
|
143 |
+
|
144 |
+
|
145 |
+
def test_list_delitem() -> None:
|
146 |
+
c = OmegaConf.create([1, 2, 3])
|
147 |
+
assert c == [1, 2, 3]
|
148 |
+
del c[0]
|
149 |
+
assert c == [2, 3]
|
150 |
+
with pytest.raises(IndexError):
|
151 |
+
del c[100]
|
152 |
+
|
153 |
+
validate_list_keys(c)
|
154 |
+
|
155 |
+
|
156 |
+
@pytest.mark.parametrize( # type: ignore
|
157 |
+
"lst,expected",
|
158 |
+
[
|
159 |
+
(OmegaConf.create([1, 2]), 2),
|
160 |
+
(ListConfig(content=None), 0),
|
161 |
+
(ListConfig(content="???"), 0),
|
162 |
+
],
|
163 |
+
)
|
164 |
+
def test_list_len(lst: Any, expected: Any) -> None:
|
165 |
+
assert len(lst) == expected
|
166 |
+
|
167 |
+
|
168 |
+
def test_nested_list_assign_illegal_value() -> None:
|
169 |
+
c = OmegaConf.create({"a": [None]})
|
170 |
+
with pytest.raises(
|
171 |
+
UnsupportedValueType,
|
172 |
+
match=re.escape(
|
173 |
+
"Value 'IllegalType' is not a supported primitive type\n\tfull_key: a[0]"
|
174 |
+
),
|
175 |
+
):
|
176 |
+
c.a[0] = IllegalType()
|
177 |
+
|
178 |
+
|
179 |
+
def test_list_append() -> None:
|
180 |
+
c = OmegaConf.create([])
|
181 |
+
c.append(1)
|
182 |
+
c.append(2)
|
183 |
+
c.append({})
|
184 |
+
c.append([])
|
185 |
+
assert c == [1, 2, {}, []]
|
186 |
+
|
187 |
+
validate_list_keys(c)
|
188 |
+
|
189 |
+
|
190 |
+
@pytest.mark.parametrize( # type: ignore
|
191 |
+
"lc,element,expected",
|
192 |
+
[
|
193 |
+
pytest.param(
|
194 |
+
ListConfig(content=[], element_type=int),
|
195 |
+
"foo",
|
196 |
+
pytest.raises(
|
197 |
+
ValidationError,
|
198 |
+
match=re.escape("Value 'foo' could not be converted to Integer"),
|
199 |
+
),
|
200 |
+
id="append_str_to_list[int]",
|
201 |
+
),
|
202 |
+
pytest.param(
|
203 |
+
ListConfig(content=[], element_type=Color),
|
204 |
+
"foo",
|
205 |
+
pytest.raises(
|
206 |
+
ValidationError,
|
207 |
+
match=re.escape(
|
208 |
+
"Invalid value 'foo', expected one of [RED, GREEN, BLUE]"
|
209 |
+
),
|
210 |
+
),
|
211 |
+
id="append_str_to_list[Color]",
|
212 |
+
),
|
213 |
+
pytest.param(
|
214 |
+
ListConfig(content=[], element_type=User),
|
215 |
+
"foo",
|
216 |
+
pytest.raises(
|
217 |
+
ValidationError,
|
218 |
+
match=re.escape(
|
219 |
+
"Invalid type assigned : str is not a subclass of User. value: foo"
|
220 |
+
),
|
221 |
+
),
|
222 |
+
id="append_str_to_list[User]",
|
223 |
+
),
|
224 |
+
pytest.param(
|
225 |
+
ListConfig(content=[], element_type=User),
|
226 |
+
{"name": "Bond", "age": 7},
|
227 |
+
pytest.raises(
|
228 |
+
ValidationError,
|
229 |
+
match=re.escape(
|
230 |
+
"Invalid type assigned : dict is not a subclass of User. value: {'name': 'Bond', 'age': 7}"
|
231 |
+
),
|
232 |
+
),
|
233 |
+
id="list:convert_dict_to_user",
|
234 |
+
),
|
235 |
+
pytest.param(
|
236 |
+
ListConfig(content=[], element_type=User),
|
237 |
+
{},
|
238 |
+
pytest.raises(
|
239 |
+
ValidationError,
|
240 |
+
match=re.escape(
|
241 |
+
"Invalid type assigned : dict is not a subclass of User. value: {}"
|
242 |
+
),
|
243 |
+
),
|
244 |
+
id="list:convert_empty_dict_to_user",
|
245 |
+
),
|
246 |
+
],
|
247 |
+
)
|
248 |
+
def test_append_invalid_element_type(
|
249 |
+
lc: ListConfig, element: Any, expected: Any
|
250 |
+
) -> None:
|
251 |
+
with expected:
|
252 |
+
lc.append(element)
|
253 |
+
|
254 |
+
|
255 |
+
@pytest.mark.parametrize( # type: ignore
|
256 |
+
"lc,element,expected",
|
257 |
+
[
|
258 |
+
pytest.param(
|
259 |
+
ListConfig(content=[], element_type=int),
|
260 |
+
"10",
|
261 |
+
10,
|
262 |
+
id="list:convert_str_to_int",
|
263 |
+
),
|
264 |
+
pytest.param(
|
265 |
+
ListConfig(content=[], element_type=float),
|
266 |
+
"10",
|
267 |
+
10.0,
|
268 |
+
id="list:convert_str_to_float",
|
269 |
+
),
|
270 |
+
pytest.param(
|
271 |
+
ListConfig(content=[], element_type=Color),
|
272 |
+
"RED",
|
273 |
+
Color.RED,
|
274 |
+
id="list:convert_str_to_float",
|
275 |
+
),
|
276 |
+
],
|
277 |
+
)
|
278 |
+
def test_append_convert(lc: ListConfig, element: Any, expected: Any) -> None:
|
279 |
+
lc.append(element)
|
280 |
+
value = lc[-1]
|
281 |
+
assert value == expected
|
282 |
+
assert type(value) == type(expected)
|
283 |
+
|
284 |
+
|
285 |
+
@pytest.mark.parametrize( # type: ignore
|
286 |
+
"index, expected", [(slice(1, 3), [11, 12]), (slice(0, 3, 2), [10, 12]), (-1, 13)]
|
287 |
+
)
|
288 |
+
def test_list_index(index: Any, expected: Any) -> None:
|
289 |
+
c = OmegaConf.create([10, 11, 12, 13])
|
290 |
+
assert c[index] == expected
|
291 |
+
|
292 |
+
|
293 |
+
@pytest.mark.parametrize( # type: ignore
|
294 |
+
"cfg, expected",
|
295 |
+
[
|
296 |
+
(OmegaConf.create([1, 2, 3]), ["0", "1", "2"]),
|
297 |
+
(ListConfig(content="???"), []),
|
298 |
+
(ListConfig(content=None), []),
|
299 |
+
],
|
300 |
+
)
|
301 |
+
def test_list_dir(cfg: Any, expected: Any) -> None:
|
302 |
+
assert dir(cfg) == expected
|
303 |
+
|
304 |
+
|
305 |
+
def validate_list_keys(c: Any) -> None:
|
306 |
+
# validate keys are maintained
|
307 |
+
for i in range(len(c)):
|
308 |
+
assert c._get_node(i)._metadata.key == i
|
309 |
+
|
310 |
+
|
311 |
+
@pytest.mark.parametrize( # type: ignore
|
312 |
+
"input_, index, value, expected, expected_node_type, expectation",
|
313 |
+
[
|
314 |
+
(["a", "b", "c"], 1, 100, ["a", 100, "b", "c"], AnyNode, None),
|
315 |
+
(
|
316 |
+
["a", "b", "c"],
|
317 |
+
1,
|
318 |
+
IntegerNode(100),
|
319 |
+
["a", 100, "b", "c"],
|
320 |
+
IntegerNode,
|
321 |
+
None,
|
322 |
+
),
|
323 |
+
(["a", "b", "c"], 1, "foo", ["a", "foo", "b", "c"], AnyNode, None),
|
324 |
+
(
|
325 |
+
["a", "b", "c"],
|
326 |
+
1,
|
327 |
+
StringNode("foo"),
|
328 |
+
["a", "foo", "b", "c"],
|
329 |
+
StringNode,
|
330 |
+
None,
|
331 |
+
),
|
332 |
+
(
|
333 |
+
ListConfig(element_type=int, content=[]),
|
334 |
+
0,
|
335 |
+
"foo",
|
336 |
+
None,
|
337 |
+
None,
|
338 |
+
ValidationError,
|
339 |
+
),
|
340 |
+
],
|
341 |
+
)
|
342 |
+
def test_insert(
|
343 |
+
input_: List[str],
|
344 |
+
index: int,
|
345 |
+
value: Any,
|
346 |
+
expected: Any,
|
347 |
+
expected_node_type: type,
|
348 |
+
expectation: Any,
|
349 |
+
) -> None:
|
350 |
+
c = OmegaConf.create(input_)
|
351 |
+
if expectation is None:
|
352 |
+
c.insert(index, value)
|
353 |
+
assert c == expected
|
354 |
+
assert type(c._get_node(index)) == expected_node_type
|
355 |
+
else:
|
356 |
+
with pytest.raises(expectation):
|
357 |
+
c.insert(index, value)
|
358 |
+
validate_list_keys(c)
|
359 |
+
|
360 |
+
|
361 |
+
@pytest.mark.parametrize( # type: ignore
|
362 |
+
"lst,idx,value,expectation",
|
363 |
+
[
|
364 |
+
(ListConfig(content=None), 0, 10, pytest.raises(TypeError)),
|
365 |
+
(ListConfig(content="???"), 0, 10, pytest.raises(MissingMandatoryValue)),
|
366 |
+
],
|
367 |
+
)
|
368 |
+
def test_insert_special_list(lst: Any, idx: Any, value: Any, expectation: Any) -> None:
|
369 |
+
with expectation:
|
370 |
+
lst.insert(idx, value)
|
371 |
+
|
372 |
+
|
373 |
+
@pytest.mark.parametrize( # type: ignore
|
374 |
+
"src, append, result",
|
375 |
+
[
|
376 |
+
([], [], []),
|
377 |
+
([1, 2], [3], [1, 2, 3]),
|
378 |
+
([1, 2], ("a", "b", "c"), [1, 2, "a", "b", "c"]),
|
379 |
+
],
|
380 |
+
)
|
381 |
+
def test_extend(src: List[Any], append: List[Any], result: List[Any]) -> None:
|
382 |
+
lst = OmegaConf.create(src)
|
383 |
+
lst.extend(append)
|
384 |
+
assert lst == result
|
385 |
+
|
386 |
+
|
387 |
+
@pytest.mark.parametrize( # type: ignore
|
388 |
+
"src, remove, result, expectation",
|
389 |
+
[
|
390 |
+
([10], 10, [], does_not_raise()),
|
391 |
+
([], "oops", None, pytest.raises(ValueError)),
|
392 |
+
([0, dict(a="blah"), 10], dict(a="blah"), [0, 10], does_not_raise()),
|
393 |
+
([1, 2, 1, 2], 2, [1, 1, 2], does_not_raise()),
|
394 |
+
],
|
395 |
+
)
|
396 |
+
def test_remove(src: List[Any], remove: Any, result: Any, expectation: Any) -> None:
|
397 |
+
with expectation:
|
398 |
+
lst = OmegaConf.create(src)
|
399 |
+
assert isinstance(lst, ListConfig)
|
400 |
+
lst.remove(remove)
|
401 |
+
assert lst == result
|
402 |
+
|
403 |
+
|
404 |
+
@pytest.mark.parametrize("src", [[], [1, 2, 3], [None, dict(foo="bar")]]) # type: ignore
|
405 |
+
@pytest.mark.parametrize("num_clears", [1, 2]) # type: ignore
|
406 |
+
def test_clear(src: List[Any], num_clears: int) -> None:
|
407 |
+
lst = OmegaConf.create(src)
|
408 |
+
for i in range(num_clears):
|
409 |
+
lst.clear()
|
410 |
+
assert lst == []
|
411 |
+
|
412 |
+
|
413 |
+
@pytest.mark.parametrize( # type: ignore
|
414 |
+
"src, item, expected_index, expectation",
|
415 |
+
[
|
416 |
+
([], 20, -1, pytest.raises(ValueError)),
|
417 |
+
([10, 20], 10, 0, does_not_raise()),
|
418 |
+
([10, 20], 20, 1, does_not_raise()),
|
419 |
+
],
|
420 |
+
)
|
421 |
+
def test_index(
|
422 |
+
src: List[Any], item: Any, expected_index: int, expectation: Any
|
423 |
+
) -> None:
|
424 |
+
with expectation:
|
425 |
+
lst = OmegaConf.create(src)
|
426 |
+
assert lst.index(item) == expected_index
|
427 |
+
|
428 |
+
|
429 |
+
def test_index_with_range() -> None:
|
430 |
+
lst = OmegaConf.create([10, 20, 30, 40, 50])
|
431 |
+
assert lst.index(x=30) == 2
|
432 |
+
assert lst.index(x=30, start=1) == 2
|
433 |
+
assert lst.index(x=30, start=1, end=3) == 2
|
434 |
+
with pytest.raises(ValueError):
|
435 |
+
lst.index(x=30, start=3)
|
436 |
+
|
437 |
+
with pytest.raises(ValueError):
|
438 |
+
lst.index(x=30, end=2)
|
439 |
+
|
440 |
+
|
441 |
+
@pytest.mark.parametrize( # type: ignore
|
442 |
+
"src, item, count",
|
443 |
+
[([], 10, 0), ([10], 10, 1), ([10, 2, 10], 10, 2), ([10, 2, 10], None, 0)],
|
444 |
+
)
|
445 |
+
def test_count(src: List[Any], item: Any, count: int) -> None:
|
446 |
+
lst = OmegaConf.create(src)
|
447 |
+
assert lst.count(item) == count
|
448 |
+
|
449 |
+
|
450 |
+
def test_sort() -> None:
|
451 |
+
c = OmegaConf.create(["bbb", "aa", "c"])
|
452 |
+
c.sort()
|
453 |
+
assert ["aa", "bbb", "c"] == c
|
454 |
+
c.sort(reverse=True)
|
455 |
+
assert ["c", "bbb", "aa"] == c
|
456 |
+
c.sort(key=len)
|
457 |
+
assert ["c", "aa", "bbb"] == c
|
458 |
+
c.sort(key=len, reverse=True)
|
459 |
+
assert ["bbb", "aa", "c"] == c
|
460 |
+
|
461 |
+
|
462 |
+
def test_insert_throws_not_changing_list() -> None:
|
463 |
+
c = OmegaConf.create([])
|
464 |
+
with pytest.raises(ValueError):
|
465 |
+
c.insert(0, IllegalType())
|
466 |
+
assert len(c) == 0
|
467 |
+
assert c == []
|
468 |
+
|
469 |
+
|
470 |
+
def test_append_throws_not_changing_list() -> None:
|
471 |
+
c = OmegaConf.create([])
|
472 |
+
v = IllegalType()
|
473 |
+
with pytest.raises(ValueError):
|
474 |
+
c.append(v)
|
475 |
+
assert len(c) == 0
|
476 |
+
assert c == []
|
477 |
+
validate_list_keys(c)
|
478 |
+
|
479 |
+
|
480 |
+
def test_hash() -> None:
|
481 |
+
c1 = OmegaConf.create([10])
|
482 |
+
c2 = OmegaConf.create([10])
|
483 |
+
assert hash(c1) == hash(c2)
|
484 |
+
c2[0] = 20
|
485 |
+
assert hash(c1) != hash(c2)
|
486 |
+
|
487 |
+
|
488 |
+
@pytest.mark.parametrize(
|
489 |
+
"in_list1, in_list2,in_expected",
|
490 |
+
[
|
491 |
+
([], [], []),
|
492 |
+
([1, 2], [3, 4], [1, 2, 3, 4]),
|
493 |
+
(["x", 2, "${0}"], [5, 6, 7], ["x", 2, "x", 5, 6, 7]),
|
494 |
+
],
|
495 |
+
)
|
496 |
+
class TestListAdd:
|
497 |
+
def test_list_plus(
|
498 |
+
self, in_list1: List[Any], in_list2: List[Any], in_expected: List[Any]
|
499 |
+
) -> None:
|
500 |
+
list1 = OmegaConf.create(in_list1)
|
501 |
+
list2 = OmegaConf.create(in_list2)
|
502 |
+
expected = OmegaConf.create(in_expected)
|
503 |
+
ret = list1 + list2
|
504 |
+
assert ret == expected
|
505 |
+
|
506 |
+
def test_list_plus_eq(
|
507 |
+
self, in_list1: List[Any], in_list2: List[Any], in_expected: List[Any]
|
508 |
+
) -> None:
|
509 |
+
list1 = OmegaConf.create(in_list1)
|
510 |
+
list2 = OmegaConf.create(in_list2)
|
511 |
+
expected = OmegaConf.create(in_expected)
|
512 |
+
list1 += list2
|
513 |
+
assert list1 == expected
|
514 |
+
|
515 |
+
|
516 |
+
def test_deep_add() -> None:
|
517 |
+
cfg = OmegaConf.create({"foo": [1, 2, "${bar}"], "bar": "xx"})
|
518 |
+
lst = cfg.foo + [10, 20]
|
519 |
+
assert lst == [1, 2, "xx", 10, 20]
|
520 |
+
|
521 |
+
|
522 |
+
def test_set_with_invalid_key() -> None:
|
523 |
+
cfg = OmegaConf.create([1, 2, 3])
|
524 |
+
with pytest.raises(KeyValidationError):
|
525 |
+
cfg["foo"] = 4 # type: ignore
|
526 |
+
|
527 |
+
|
528 |
+
@pytest.mark.parametrize( # type: ignore
|
529 |
+
"lst,idx,expected",
|
530 |
+
[
|
531 |
+
(OmegaConf.create([1, 2]), 0, 1),
|
532 |
+
(ListConfig(content=None), 0, TypeError),
|
533 |
+
(ListConfig(content="???"), 0, MissingMandatoryValue),
|
534 |
+
],
|
535 |
+
)
|
536 |
+
def test_getitem(lst: Any, idx: Any, expected: Any) -> None:
|
537 |
+
if isinstance(expected, type):
|
538 |
+
with pytest.raises(expected):
|
539 |
+
lst.__getitem__(idx)
|
540 |
+
else:
|
541 |
+
assert lst.__getitem__(idx) == expected
|
542 |
+
|
543 |
+
|
544 |
+
@pytest.mark.parametrize( # type: ignore
|
545 |
+
"sli",
|
546 |
+
[
|
547 |
+
(slice(None, None, None)),
|
548 |
+
(slice(1, None, None)),
|
549 |
+
(slice(-1, None, None)),
|
550 |
+
(slice(None, 1, None)),
|
551 |
+
(slice(None, -1, None)),
|
552 |
+
(slice(None, None, 1)),
|
553 |
+
(slice(None, None, -1)),
|
554 |
+
(slice(1, None, -2)),
|
555 |
+
(slice(None, 1, -2)),
|
556 |
+
(slice(1, 3, -1)),
|
557 |
+
(slice(3, 1, -1)),
|
558 |
+
],
|
559 |
+
)
|
560 |
+
def test_getitem_slice(sli: slice) -> None:
|
561 |
+
lst = [1, 2, 3]
|
562 |
+
olst = OmegaConf.create([1, 2, 3])
|
563 |
+
expected = lst[sli.start : sli.stop : sli.step]
|
564 |
+
assert olst.__getitem__(sli) == expected
|
565 |
+
|
566 |
+
|
567 |
+
@pytest.mark.parametrize( # type: ignore
|
568 |
+
"lst,idx,expected",
|
569 |
+
[
|
570 |
+
(OmegaConf.create([1, 2]), 0, 1),
|
571 |
+
(OmegaConf.create([1, 2]), "foo", KeyValidationError),
|
572 |
+
(ListConfig(content=None), 0, TypeError),
|
573 |
+
(ListConfig(content="???"), 0, MissingMandatoryValue),
|
574 |
+
],
|
575 |
+
)
|
576 |
+
def test_get(lst: Any, idx: Any, expected: Any) -> None:
|
577 |
+
if isinstance(expected, type):
|
578 |
+
with pytest.raises(expected):
|
579 |
+
lst.get(idx)
|
580 |
+
else:
|
581 |
+
lst.__getitem__(idx) == expected
|
582 |
+
|
583 |
+
|
584 |
+
def test_getattr() -> None:
|
585 |
+
src = ["a", "b", "c"]
|
586 |
+
cfg = OmegaConf.create(src)
|
587 |
+
with pytest.raises(AttributeError):
|
588 |
+
getattr(cfg, "foo")
|
589 |
+
assert getattr(cfg, "0") == src[0]
|
590 |
+
assert getattr(cfg, "1") == src[1]
|
591 |
+
assert getattr(cfg, "2") == src[2]
|
tests/test_config_eq.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
from omegaconf import AnyNode, DictConfig, ListConfig, OmegaConf
|
6 |
+
|
7 |
+
from . import Group, User
|
8 |
+
|
9 |
+
|
10 |
+
@pytest.mark.parametrize( # type: ignore
|
11 |
+
"i1,i2",
|
12 |
+
[
|
13 |
+
# === LISTS ===
|
14 |
+
# empty list
|
15 |
+
pytest.param([], [], id="empty"),
|
16 |
+
# simple list
|
17 |
+
pytest.param(["a", 12, "15"], ["a", 12, "15"], id="simple_list"),
|
18 |
+
# raw vs any
|
19 |
+
([1, 2, 12], [1, 2, AnyNode(12)]),
|
20 |
+
# nested empty dict
|
21 |
+
([12, {}], [12, {}]),
|
22 |
+
# nested dict
|
23 |
+
([12, {"c": 10}], [12, {"c": 10}]),
|
24 |
+
# nested list
|
25 |
+
([1, 2, 3, [10, 20, 30]], [1, 2, 3, [10, 20, 30]]),
|
26 |
+
# nested list with any
|
27 |
+
([1, 2, 3, [1, 2, AnyNode(3)]], [1, 2, 3, [1, 2, AnyNode(3)]]),
|
28 |
+
# === DICTS ===
|
29 |
+
# empty
|
30 |
+
({}, {}),
|
31 |
+
# simple
|
32 |
+
({"a": 12}, {"a": 12}),
|
33 |
+
# any vs raw
|
34 |
+
({"a": 12}, {"a": AnyNode(12)}),
|
35 |
+
# nested dict empty
|
36 |
+
(dict(a=12, b=dict()), dict(a=12, b=dict())),
|
37 |
+
# nested dict
|
38 |
+
(dict(a=12, b=dict(c=10)), dict(a=12, b=dict(c=10))),
|
39 |
+
# nested list
|
40 |
+
(dict(a=12, b=[1, 2, 3]), dict(a=12, b=[1, 2, 3])),
|
41 |
+
# nested list with any
|
42 |
+
(dict(a=12, b=[1, 2, AnyNode(3)]), dict(a=12, b=[1, 2, AnyNode(3)])),
|
43 |
+
# In python 3.6+ insert order changes iteration order. this ensures that equality is preserved.
|
44 |
+
(dict(a=1, b=2, c=3, d=4, e=5), dict(e=5, b=2, c=3, d=4, a=1)),
|
45 |
+
(DictConfig(content=None), DictConfig(content=None)),
|
46 |
+
pytest.param({"a": [1, 2]}, {"a": [1, 2]}, id="list_in_dict"),
|
47 |
+
# With interpolations
|
48 |
+
([10, "${0}"], [10, 10]),
|
49 |
+
(dict(a=12, b="${a}"), dict(a=12, b=12)),
|
50 |
+
# With missing interpolation
|
51 |
+
pytest.param([10, "${0}"], [10, 10], id="list_simple_interpolation"),
|
52 |
+
pytest.param(
|
53 |
+
{"a": "${ref_error}"}, {"a": "${ref_error}"}, id="dict==dict,ref_error"
|
54 |
+
),
|
55 |
+
pytest.param({"a": "???"}, {"a": "???"}, id="dict==dict,missing"),
|
56 |
+
pytest.param(User, User, id="User==User"),
|
57 |
+
pytest.param(
|
58 |
+
{"name": "poo", "age": 7}, User(name="poo", age=7), id="dict==User"
|
59 |
+
),
|
60 |
+
pytest.param(Group, Group, id="Group==Group"),
|
61 |
+
pytest.param({"group": {"admin": None}}, {"group": Group}, id="dict==Group"),
|
62 |
+
pytest.param(
|
63 |
+
{"i1": "${n1}", "n1": {"a": 10}},
|
64 |
+
{"i1": "${n1}", "n1": {"a": 10}},
|
65 |
+
id="node_interpolation",
|
66 |
+
),
|
67 |
+
# Inter containers
|
68 |
+
pytest.param(
|
69 |
+
{"foo": DictConfig(content="${bar}"), "bar": 10},
|
70 |
+
{"foo": 10, "bar": 10},
|
71 |
+
id="dictconfig_inter",
|
72 |
+
),
|
73 |
+
pytest.param(
|
74 |
+
{"foo": ListConfig(content="${bar}"), "bar": 10},
|
75 |
+
{"foo": 10, "bar": 10},
|
76 |
+
id="listconfig_inter",
|
77 |
+
),
|
78 |
+
# None containers
|
79 |
+
pytest.param(
|
80 |
+
{"foo": DictConfig(content=None)}, {"foo": None}, id="dictconfig_none"
|
81 |
+
),
|
82 |
+
pytest.param(
|
83 |
+
{"foo": ListConfig(content=None)}, {"foo": None}, id="listconfig_none"
|
84 |
+
),
|
85 |
+
# Missing containers
|
86 |
+
pytest.param(
|
87 |
+
{"foo": DictConfig(content="???")}, {"foo": "???"}, id="dictconfig_missing"
|
88 |
+
),
|
89 |
+
pytest.param(
|
90 |
+
{"foo": ListConfig(content="???")}, {"foo": "???"}, id="listconfig_missing"
|
91 |
+
),
|
92 |
+
],
|
93 |
+
)
|
94 |
+
def test_eq(i1: Any, i2: Any) -> None:
|
95 |
+
c1 = OmegaConf.create(i1)
|
96 |
+
c2 = OmegaConf.create(i2)
|
97 |
+
|
98 |
+
def eq(a: Any, b: Any) -> None:
|
99 |
+
assert a == b
|
100 |
+
assert b == a
|
101 |
+
assert not a != b
|
102 |
+
assert not b != a
|
103 |
+
|
104 |
+
eq(c1, c2)
|
105 |
+
eq(c1, i1)
|
106 |
+
eq(c2, i2)
|
107 |
+
|
108 |
+
|
109 |
+
@pytest.mark.parametrize( # type: ignore
|
110 |
+
"input1, input2",
|
111 |
+
[
|
112 |
+
# Dicts
|
113 |
+
pytest.param({}, {"a": 10}, id="empty_dict_neq_dict"),
|
114 |
+
pytest.param({}, [], id="empty_dict_vs_list"),
|
115 |
+
pytest.param({}, None, id="dict_neq_none"),
|
116 |
+
pytest.param({"foo": None}, {"foo": "bar"}, id="dict_none_neq_dict_not_none"),
|
117 |
+
pytest.param({"a": 12}, {"a": 13}, id="simple_dict_neq"),
|
118 |
+
pytest.param({"a": 0}, {"b": 0}, id="different_key_same_value"),
|
119 |
+
pytest.param(dict(a=12), dict(a=AnyNode(13))),
|
120 |
+
pytest.param(dict(a=12, b=dict()), dict(a=13, b=dict())),
|
121 |
+
pytest.param(dict(a=12, b=dict(c=10)), dict(a=13, b=dict(c=10))),
|
122 |
+
pytest.param(dict(a=12, b=[1, 2, 3]), dict(a=12, b=[10, 2, 3])),
|
123 |
+
pytest.param(
|
124 |
+
dict(a=12, b=[1, 2, AnyNode(3)]), dict(a=12, b=[1, 2, AnyNode(30)])
|
125 |
+
),
|
126 |
+
# Lists
|
127 |
+
pytest.param([], [10], id="list:empty_vs_full"),
|
128 |
+
pytest.param([10], [11], id="list:different_value"),
|
129 |
+
([12], [AnyNode(13)]),
|
130 |
+
([12, dict()], [13, dict()]),
|
131 |
+
([12, dict(c=10)], [13, dict(c=10)]),
|
132 |
+
([12, [1, 2, 3]], [12, [10, 2, 3]]),
|
133 |
+
([12, [1, 2, AnyNode(3)]], [12, [1, 2, AnyNode(30)]]),
|
134 |
+
(dict(a="${foo1}"), dict(a="${foo2}")),
|
135 |
+
pytest.param(
|
136 |
+
{"i1": "${n1}", "n1": {"a": 10}},
|
137 |
+
{"i1": "${n1}", "n1": {"a": 20}},
|
138 |
+
id="node_interpolation",
|
139 |
+
),
|
140 |
+
],
|
141 |
+
)
|
142 |
+
def test_not_eq(input1: Any, input2: Any) -> None:
|
143 |
+
c1 = OmegaConf.create(input1)
|
144 |
+
c2 = OmegaConf.create(input2)
|
145 |
+
|
146 |
+
def neq(a: Any, b: Any) -> None:
|
147 |
+
assert a != b
|
148 |
+
assert b != a
|
149 |
+
assert not a == b
|
150 |
+
assert not b == a
|
151 |
+
|
152 |
+
neq(c1, c2)
|
153 |
+
neq(c2, c1)
|
154 |
+
|
155 |
+
|
156 |
+
# ---
|
157 |
+
def test_config_eq_mismatch_types() -> None:
|
158 |
+
c1 = OmegaConf.create({})
|
159 |
+
c2 = OmegaConf.create([])
|
160 |
+
assert c1 != c2
|
161 |
+
|
162 |
+
|
163 |
+
def test_dict_not_eq_with_another_class() -> None:
|
164 |
+
assert OmegaConf.create({}) != "string"
|
165 |
+
assert OmegaConf.create([]) != "string"
|
tests/test_create.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Testing for OmegaConf"""
|
2 |
+
import re
|
3 |
+
import sys
|
4 |
+
from typing import Any, Dict, List
|
5 |
+
|
6 |
+
import pytest
|
7 |
+
import yaml
|
8 |
+
|
9 |
+
from omegaconf import DictConfig, ListConfig, OmegaConf
|
10 |
+
from omegaconf.errors import UnsupportedValueType
|
11 |
+
|
12 |
+
from . import ConcretePlugin, IllegalType, Plugin
|
13 |
+
|
14 |
+
|
15 |
+
@pytest.mark.parametrize( # type: ignore
|
16 |
+
"input_,expected",
|
17 |
+
[
|
18 |
+
# No content
|
19 |
+
(None, None),
|
20 |
+
# empty
|
21 |
+
({}, {}),
|
22 |
+
# simple value
|
23 |
+
("hello", {"hello": None}),
|
24 |
+
# simple key:value"
|
25 |
+
("hello: world", {"hello": "world"}),
|
26 |
+
({"hello": {"a": 2}}, {"hello": {"a": 2}}),
|
27 |
+
# empty input
|
28 |
+
("", {}),
|
29 |
+
# list value
|
30 |
+
([1, 2], [1, 2]),
|
31 |
+
# For simplicity, tuples are converted to lists.
|
32 |
+
((1, 2), [1, 2]),
|
33 |
+
# dict 1
|
34 |
+
({"a": 2, "b": 10}, {"a": 2, "b": 10}),
|
35 |
+
# dict 2
|
36 |
+
(dict(a=2, b=10), dict(a=2, b=10)),
|
37 |
+
# nested dict
|
38 |
+
(
|
39 |
+
{"a": 2, "b": {"c": {"f": 1}, "d": {}}},
|
40 |
+
{"a": 2, "b": {"c": {"f": 1}, "d": {}}},
|
41 |
+
),
|
42 |
+
({"a": None}, {"a": None}),
|
43 |
+
({"foo": "${missing}"}, {"foo": "${missing}"}),
|
44 |
+
(OmegaConf.create({"foo": "${missing}"}), {"foo": "${missing}"}),
|
45 |
+
(OmegaConf.create(), {}),
|
46 |
+
(OmegaConf.create({}), {}),
|
47 |
+
(OmegaConf.create([]), []),
|
48 |
+
(OmegaConf.create({"foo": OmegaConf.create([])}), {"foo": []}),
|
49 |
+
(OmegaConf.create([OmegaConf.create({})]), [{}]), # type: ignore
|
50 |
+
],
|
51 |
+
)
|
52 |
+
def test_create_value(input_: Any, expected: Any) -> None:
|
53 |
+
assert OmegaConf.create(input_) == expected
|
54 |
+
|
55 |
+
|
56 |
+
def test_create_from_cli() -> None:
|
57 |
+
sys.argv = ["program.py", "a=1", "b.c=2"]
|
58 |
+
c = OmegaConf.from_cli()
|
59 |
+
assert {"a": 1, "b": {"c": 2}} == c
|
60 |
+
|
61 |
+
|
62 |
+
def test_cli_passing() -> None:
|
63 |
+
args_list = ["a=1", "b.c=2"]
|
64 |
+
c = OmegaConf.from_cli(args_list)
|
65 |
+
assert {"a": 1, "b": {"c": 2}} == c
|
66 |
+
|
67 |
+
|
68 |
+
@pytest.mark.parametrize( # type: ignore
|
69 |
+
"input_,expected",
|
70 |
+
[
|
71 |
+
# simple
|
72 |
+
(["a=1", "b.c=2"], dict(a=1, b=dict(c=2))),
|
73 |
+
# string
|
74 |
+
(["a=hello", "b=world"], dict(a="hello", b="world")),
|
75 |
+
# date-formatted string
|
76 |
+
(["my_date=2019-12-11"], dict(my_date="2019-12-11")),
|
77 |
+
],
|
78 |
+
)
|
79 |
+
def test_dotlist(input_: List[str], expected: Dict[str, Any]) -> None:
|
80 |
+
c = OmegaConf.from_dotlist(input_)
|
81 |
+
assert c == expected
|
82 |
+
|
83 |
+
|
84 |
+
def test_create_list_with_illegal_value_idx0() -> None:
|
85 |
+
with pytest.raises(UnsupportedValueType, match=re.escape("key: [0]")):
|
86 |
+
OmegaConf.create([IllegalType()])
|
87 |
+
|
88 |
+
|
89 |
+
def test_create_list_with_illegal_value_idx1() -> None:
|
90 |
+
lst = [1, IllegalType(), 3]
|
91 |
+
with pytest.raises(UnsupportedValueType, match=re.escape("key: [1]")):
|
92 |
+
OmegaConf.create(lst)
|
93 |
+
|
94 |
+
|
95 |
+
def test_create_dict_with_illegal_value() -> None:
|
96 |
+
with pytest.raises(UnsupportedValueType, match=re.escape("key: a")):
|
97 |
+
OmegaConf.create({"a": IllegalType()})
|
98 |
+
|
99 |
+
|
100 |
+
def test_create_nested_dict_with_illegal_value() -> None:
|
101 |
+
with pytest.raises(ValueError, match=re.escape("key: a.b")):
|
102 |
+
OmegaConf.create({"a": {"b": IllegalType()}})
|
103 |
+
|
104 |
+
|
105 |
+
def test_create_from_oc() -> None:
|
106 |
+
c = OmegaConf.create(
|
107 |
+
{"a": OmegaConf.create([1, 2, 3]), "b": OmegaConf.create({"c": 10})}
|
108 |
+
)
|
109 |
+
assert c == {"a": [1, 2, 3], "b": {"c": 10}}
|
110 |
+
|
111 |
+
|
112 |
+
def test_create_from_oc_with_flags() -> None:
|
113 |
+
c1 = OmegaConf.create({"foo": "bar"})
|
114 |
+
OmegaConf.set_struct(c1, True)
|
115 |
+
c2 = OmegaConf.create(c1)
|
116 |
+
assert c1 == c2
|
117 |
+
assert c1._metadata.flags == c2._metadata.flags
|
118 |
+
|
119 |
+
|
120 |
+
def test_create_from_dictconfig_preserves_metadata() -> None:
|
121 |
+
cfg1 = DictConfig(ref_type=Plugin, is_optional=False, content=ConcretePlugin)
|
122 |
+
OmegaConf.set_struct(cfg1, True)
|
123 |
+
OmegaConf.set_readonly(cfg1, True)
|
124 |
+
cfg2 = OmegaConf.create(cfg1)
|
125 |
+
assert cfg1 == cfg2
|
126 |
+
assert cfg1._metadata == cfg2._metadata
|
127 |
+
|
128 |
+
|
129 |
+
def test_create_from_listconfig_preserves_metadata() -> None:
|
130 |
+
cfg1 = ListConfig(element_type=int, is_optional=False, content=[1, 2, 3])
|
131 |
+
OmegaConf.set_struct(cfg1, True)
|
132 |
+
OmegaConf.set_readonly(cfg1, True)
|
133 |
+
cfg2 = OmegaConf.create(cfg1)
|
134 |
+
assert cfg1 == cfg2
|
135 |
+
assert cfg1._metadata == cfg2._metadata
|
136 |
+
|
137 |
+
|
138 |
+
@pytest.mark.parametrize("node", [({"bar": 10}), ([1, 2, 3])]) # type: ignore
|
139 |
+
def test_create_node_parent_retained_on_create(node: Any) -> None:
|
140 |
+
cfg1 = OmegaConf.create({"foo": node})
|
141 |
+
cfg2 = OmegaConf.create({"zonk": cfg1.foo})
|
142 |
+
assert cfg2 == {"zonk": node}
|
143 |
+
assert cfg1.foo._get_parent() == cfg1
|
144 |
+
|
145 |
+
|
146 |
+
def test_create_unmodified_loader() -> None:
|
147 |
+
cfg = OmegaConf.create("gitrev: 100e100")
|
148 |
+
yaml_cfg = yaml.load("gitrev: 100e100", Loader=yaml.loader.SafeLoader)
|
149 |
+
assert cfg.gitrev == 1e102
|
150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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from dataclasses import dataclass
|
3 |
+
from enum import Enum
|
4 |
+
from typing import Any, Dict, List, Optional, Type, Union
|
5 |
+
|
6 |
+
import pytest
|
7 |
+
|
8 |
+
from omegaconf import (
|
9 |
+
DictConfig,
|
10 |
+
IntegerNode,
|
11 |
+
ListConfig,
|
12 |
+
OmegaConf,
|
13 |
+
ReadonlyConfigError,
|
14 |
+
UnsupportedValueType,
|
15 |
+
ValidationError,
|
16 |
+
)
|
17 |
+
from omegaconf.errors import (
|
18 |
+
ConfigAttributeError,
|
19 |
+
ConfigKeyError,
|
20 |
+
ConfigTypeError,
|
21 |
+
ConfigValueError,
|
22 |
+
KeyValidationError,
|
23 |
+
MissingMandatoryValue,
|
24 |
+
OmegaConfBaseException,
|
25 |
+
)
|
26 |
+
|
27 |
+
from . import (
|
28 |
+
A,
|
29 |
+
Color,
|
30 |
+
ConcretePlugin,
|
31 |
+
IllegalType,
|
32 |
+
Module,
|
33 |
+
Package,
|
34 |
+
Plugin,
|
35 |
+
StructuredWithMissing,
|
36 |
+
UnionError,
|
37 |
+
User,
|
38 |
+
)
|
39 |
+
|
40 |
+
|
41 |
+
# tests classes
|
42 |
+
@dataclass
|
43 |
+
class NotOptionalInt:
|
44 |
+
foo: int = None # type:ignore
|
45 |
+
|
46 |
+
|
47 |
+
@dataclass
|
48 |
+
class NotOptionalA:
|
49 |
+
x: A = None # type: ignore
|
50 |
+
|
51 |
+
|
52 |
+
@dataclass
|
53 |
+
class Expected:
|
54 |
+
exception_type: Type[Exception]
|
55 |
+
msg: str
|
56 |
+
|
57 |
+
# "Low level exceptions" are thrown from internal APIs are are not populating all the fields
|
58 |
+
low_level: bool = False
|
59 |
+
key: Any = None
|
60 |
+
# "AUTO" : determine automatically based on OmegaConf.get_type(cfg)
|
61 |
+
object_type: Any = "AUTO"
|
62 |
+
ref_type: Any = None
|
63 |
+
|
64 |
+
# "AUTO: full_key is key
|
65 |
+
full_key: Any = "AUTO"
|
66 |
+
create: Any = lambda: None
|
67 |
+
op: Any = lambda _cfg: None
|
68 |
+
child_node: Any = lambda cfg: None
|
69 |
+
parent_node: Any = lambda cfg: cfg
|
70 |
+
|
71 |
+
object_type_str: Optional[str] = "AUTO"
|
72 |
+
ref_type_str: Optional[str] = "AUTO"
|
73 |
+
num_lines: int = 3
|
74 |
+
|
75 |
+
def finalize(self, cfg: Any) -> None:
|
76 |
+
if self.object_type == "AUTO":
|
77 |
+
self.object_type = OmegaConf.get_type(cfg)
|
78 |
+
|
79 |
+
if self.full_key == "AUTO":
|
80 |
+
if self.key is None:
|
81 |
+
self.full_key = ""
|
82 |
+
else:
|
83 |
+
if isinstance(self.key, (str, int, Enum, slice)):
|
84 |
+
self.full_key = self.key
|
85 |
+
else:
|
86 |
+
self.full_key = ""
|
87 |
+
|
88 |
+
|
89 |
+
params = [
|
90 |
+
##############
|
91 |
+
# DictConfig #
|
92 |
+
##############
|
93 |
+
# update
|
94 |
+
pytest.param(
|
95 |
+
Expected(
|
96 |
+
create=lambda: OmegaConf.structured(StructuredWithMissing),
|
97 |
+
op=lambda cfg: OmegaConf.update(cfg, "num", "hello", merge=True),
|
98 |
+
exception_type=ValidationError,
|
99 |
+
msg="Value 'hello' could not be converted to Integer",
|
100 |
+
parent_node=lambda cfg: cfg,
|
101 |
+
child_node=lambda cfg: cfg._get_node("num"),
|
102 |
+
object_type=StructuredWithMissing,
|
103 |
+
ref_type=Optional[StructuredWithMissing],
|
104 |
+
key="num",
|
105 |
+
),
|
106 |
+
id="structured:update_with_invalid_value",
|
107 |
+
),
|
108 |
+
pytest.param(
|
109 |
+
Expected(
|
110 |
+
create=lambda: OmegaConf.structured(StructuredWithMissing),
|
111 |
+
op=lambda cfg: OmegaConf.update(cfg, "num", None, merge=True),
|
112 |
+
exception_type=ValidationError,
|
113 |
+
msg="child 'num' is not Optional",
|
114 |
+
parent_node=lambda cfg: cfg,
|
115 |
+
child_node=lambda cfg: cfg._get_node("num"),
|
116 |
+
object_type=StructuredWithMissing,
|
117 |
+
ref_type=Optional[StructuredWithMissing],
|
118 |
+
key="num",
|
119 |
+
),
|
120 |
+
id="structured:update:none_to_non_optional",
|
121 |
+
),
|
122 |
+
pytest.param(
|
123 |
+
Expected(
|
124 |
+
create=lambda: OmegaConf.create({}),
|
125 |
+
op=lambda cfg: OmegaConf.update(cfg, "a", IllegalType(), merge=True),
|
126 |
+
key="a",
|
127 |
+
exception_type=UnsupportedValueType,
|
128 |
+
ref_type=Optional[Dict[Union[str, Enum], Any]],
|
129 |
+
msg="Value 'IllegalType' is not a supported primitive type",
|
130 |
+
),
|
131 |
+
id="dict:update:object_of_illegal_type",
|
132 |
+
),
|
133 |
+
# pop
|
134 |
+
pytest.param(
|
135 |
+
Expected(
|
136 |
+
create=lambda: create_readonly({"foo": "bar"}),
|
137 |
+
op=lambda cfg: cfg.pop("foo"),
|
138 |
+
key="foo",
|
139 |
+
child_node=lambda cfg: cfg._get_node("foo"),
|
140 |
+
exception_type=ReadonlyConfigError,
|
141 |
+
ref_type=Optional[Dict[Union[str, Enum], Any]],
|
142 |
+
msg="Cannot pop from read-only node",
|
143 |
+
),
|
144 |
+
id="dict,readonly:pop",
|
145 |
+
),
|
146 |
+
pytest.param(
|
147 |
+
Expected(
|
148 |
+
create=lambda: OmegaConf.create({"foo": "bar"}),
|
149 |
+
op=lambda cfg: cfg.pop("nevermind"),
|
150 |
+
key="nevermind",
|
151 |
+
exception_type=ConfigKeyError,
|
152 |
+
msg="Key not found: 'nevermind'",
|
153 |
+
),
|
154 |
+
id="dict:pop_invalid",
|
155 |
+
),
|
156 |
+
pytest.param(
|
157 |
+
Expected(
|
158 |
+
create=lambda: OmegaConf.create({"foo": {}}),
|
159 |
+
op=lambda cfg: cfg.foo.pop("nevermind"),
|
160 |
+
key="nevermind",
|
161 |
+
full_key="foo.nevermind",
|
162 |
+
parent_node=lambda cfg: cfg.foo,
|
163 |
+
exception_type=ConfigKeyError,
|
164 |
+
msg="Key not found: 'nevermind' (path: 'foo.nevermind')",
|
165 |
+
),
|
166 |
+
id="dict:pop_invalid_nested",
|
167 |
+
),
|
168 |
+
pytest.param(
|
169 |
+
Expected(
|
170 |
+
create=lambda: OmegaConf.structured(ConcretePlugin),
|
171 |
+
op=lambda cfg: getattr(cfg, "fail"),
|
172 |
+
exception_type=ConfigAttributeError,
|
173 |
+
msg="Key 'fail' not in 'ConcretePlugin'",
|
174 |
+
key="fail",
|
175 |
+
object_type=ConcretePlugin,
|
176 |
+
ref_type=Optional[ConcretePlugin],
|
177 |
+
),
|
178 |
+
id="structured:access_invalid_attribute",
|
179 |
+
),
|
180 |
+
# getattr
|
181 |
+
pytest.param(
|
182 |
+
Expected(
|
183 |
+
create=lambda: create_struct({"foo": "bar"}),
|
184 |
+
op=lambda cfg: getattr(cfg, "fail"),
|
185 |
+
exception_type=ConfigAttributeError,
|
186 |
+
msg="Key 'fail' is not in struct",
|
187 |
+
key="fail",
|
188 |
+
),
|
189 |
+
id="dict,struct:access_invalid_attribute",
|
190 |
+
),
|
191 |
+
pytest.param(
|
192 |
+
Expected(
|
193 |
+
create=lambda: OmegaConf.create({"foo": "${missing}"}),
|
194 |
+
op=lambda cfg: getattr(cfg, "foo"),
|
195 |
+
exception_type=ConfigKeyError,
|
196 |
+
msg="str interpolation key 'missing' not found",
|
197 |
+
key="foo",
|
198 |
+
child_node=lambda cfg: cfg._get_node("foo"),
|
199 |
+
),
|
200 |
+
id="dict,accessing_missing_interpolation",
|
201 |
+
),
|
202 |
+
pytest.param(
|
203 |
+
Expected(
|
204 |
+
create=lambda: OmegaConf.create({"foo": "foo_${missing}"}),
|
205 |
+
op=lambda cfg: getattr(cfg, "foo"),
|
206 |
+
exception_type=ConfigKeyError,
|
207 |
+
msg="str interpolation key 'missing' not found",
|
208 |
+
key="foo",
|
209 |
+
child_node=lambda cfg: cfg._get_node("foo"),
|
210 |
+
),
|
211 |
+
id="dict,accessing_missing_str_interpolation",
|
212 |
+
),
|
213 |
+
# setattr
|
214 |
+
pytest.param(
|
215 |
+
Expected(
|
216 |
+
create=lambda: create_struct({"foo": "bar"}),
|
217 |
+
op=lambda cfg: setattr(cfg, "zlonk", "zlank"),
|
218 |
+
exception_type=ConfigAttributeError,
|
219 |
+
msg="Key 'zlonk' is not in struct",
|
220 |
+
key="zlonk",
|
221 |
+
),
|
222 |
+
id="dict,struct:set_invalid_attribute",
|
223 |
+
),
|
224 |
+
pytest.param(
|
225 |
+
Expected(
|
226 |
+
create=lambda: OmegaConf.structured(ConcretePlugin),
|
227 |
+
op=lambda cfg: setattr(cfg, "params", 20),
|
228 |
+
exception_type=ValidationError,
|
229 |
+
msg="Invalid type assigned : int is not a subclass of FoobarParams. value: 20",
|
230 |
+
key="params",
|
231 |
+
object_type=ConcretePlugin,
|
232 |
+
ref_type=Optional[ConcretePlugin],
|
233 |
+
child_node=lambda cfg: cfg.params,
|
234 |
+
),
|
235 |
+
id="structured:setattr,invalid_type_assigned_to_structured",
|
236 |
+
),
|
237 |
+
pytest.param(
|
238 |
+
Expected(
|
239 |
+
create=lambda: create_readonly({"foo": "bar"}),
|
240 |
+
op=lambda cfg: setattr(cfg, "foo", 20),
|
241 |
+
exception_type=ReadonlyConfigError,
|
242 |
+
msg="Cannot change read-only config container",
|
243 |
+
key="foo",
|
244 |
+
child_node=lambda cfg: cfg.foo,
|
245 |
+
),
|
246 |
+
id="dict,readonly:set_attribute",
|
247 |
+
),
|
248 |
+
pytest.param(
|
249 |
+
Expected(
|
250 |
+
create=lambda: OmegaConf.create(
|
251 |
+
{"foo": DictConfig(is_optional=False, content={})}
|
252 |
+
),
|
253 |
+
op=lambda cfg: setattr(cfg, "foo", None),
|
254 |
+
exception_type=ValidationError,
|
255 |
+
msg="child 'foo' is not Optional",
|
256 |
+
key="foo",
|
257 |
+
full_key="foo",
|
258 |
+
child_node=lambda cfg: cfg.foo,
|
259 |
+
),
|
260 |
+
id="dict:setattr:not_optional:set_none",
|
261 |
+
),
|
262 |
+
pytest.param(
|
263 |
+
Expected(
|
264 |
+
create=lambda: OmegaConf.structured(ConcretePlugin),
|
265 |
+
op=lambda cfg: cfg.params.__setattr__("foo", "bar"),
|
266 |
+
exception_type=ValidationError,
|
267 |
+
msg="Value 'bar' could not be converted to Integer",
|
268 |
+
key="foo",
|
269 |
+
full_key="params.foo",
|
270 |
+
object_type=ConcretePlugin.FoobarParams,
|
271 |
+
child_node=lambda cfg: cfg.params.foo,
|
272 |
+
parent_node=lambda cfg: cfg.params,
|
273 |
+
),
|
274 |
+
id="structured:setattr,invalid_type_assigned_to_field",
|
275 |
+
),
|
276 |
+
# setitem
|
277 |
+
pytest.param(
|
278 |
+
Expected(
|
279 |
+
create=lambda: create_struct({"foo": "bar"}),
|
280 |
+
op=lambda cfg: cfg.__setitem__("zoo", "zonk"),
|
281 |
+
exception_type=KeyError,
|
282 |
+
msg="Key 'zoo' is not in struct",
|
283 |
+
key="zoo",
|
284 |
+
),
|
285 |
+
id="dict,struct:setitem_on_none_existing_key",
|
286 |
+
),
|
287 |
+
pytest.param(
|
288 |
+
Expected(
|
289 |
+
create=lambda: DictConfig(key_type=Color, element_type=str, content={}),
|
290 |
+
op=lambda cfg: cfg.__setitem__("foo", "bar"),
|
291 |
+
exception_type=KeyValidationError,
|
292 |
+
msg="Key 'foo' is incompatible with the enum type 'Color', valid: [RED, GREEN, BLUE]",
|
293 |
+
full_key="foo",
|
294 |
+
key="foo",
|
295 |
+
),
|
296 |
+
id="DictConfig[Color,str]:setitem_bad_key",
|
297 |
+
),
|
298 |
+
pytest.param(
|
299 |
+
Expected(
|
300 |
+
create=lambda: DictConfig(key_type=str, element_type=Color, content={}),
|
301 |
+
op=lambda cfg: cfg.__setitem__("foo", "bar"),
|
302 |
+
exception_type=ValidationError,
|
303 |
+
msg="Invalid value 'bar', expected one of [RED, GREEN, BLUE]",
|
304 |
+
full_key="foo",
|
305 |
+
key="foo",
|
306 |
+
),
|
307 |
+
id="DictConfig[str,Color]:setitem_bad_value",
|
308 |
+
),
|
309 |
+
pytest.param(
|
310 |
+
Expected(
|
311 |
+
create=lambda: OmegaConf.structured(User),
|
312 |
+
op=lambda cfg: cfg.__setitem__("name", [1, 2]),
|
313 |
+
exception_type=ValidationError,
|
314 |
+
msg="Cannot convert 'list' to string : '[1, 2]'",
|
315 |
+
full_key="name",
|
316 |
+
key="name",
|
317 |
+
low_level=True,
|
318 |
+
),
|
319 |
+
id="DictConfig[Any,Any]:setitem_stringnode_bad_value",
|
320 |
+
),
|
321 |
+
# getitem
|
322 |
+
pytest.param(
|
323 |
+
Expected(
|
324 |
+
create=lambda: create_struct({"foo": "bar"}),
|
325 |
+
op=lambda cfg: cfg.__getitem__("zoo"),
|
326 |
+
exception_type=KeyError,
|
327 |
+
msg="Key 'zoo' is not in struct",
|
328 |
+
key="zoo",
|
329 |
+
),
|
330 |
+
id="dict,struct:getitem_key_not_in_struct",
|
331 |
+
),
|
332 |
+
pytest.param(
|
333 |
+
Expected(
|
334 |
+
create=lambda: DictConfig(key_type=Color, element_type=str, content={}),
|
335 |
+
op=lambda cfg: cfg.__getitem__("foo"),
|
336 |
+
exception_type=KeyValidationError,
|
337 |
+
msg="Key 'foo' is incompatible with the enum type 'Color', valid: [RED, GREEN, BLUE]",
|
338 |
+
key="foo",
|
339 |
+
num_lines=3,
|
340 |
+
),
|
341 |
+
id="DictConfig[Color,str]:getitem_str_key",
|
342 |
+
),
|
343 |
+
pytest.param(
|
344 |
+
Expected(
|
345 |
+
create=lambda: DictConfig(key_type=str, element_type=str, content={}),
|
346 |
+
op=lambda cfg: cfg.__getitem__(Color.RED),
|
347 |
+
exception_type=KeyValidationError,
|
348 |
+
msg="Key Color.RED (Color) is incompatible with (str)",
|
349 |
+
full_key="RED",
|
350 |
+
key=Color.RED,
|
351 |
+
),
|
352 |
+
id="DictConfig[str,str]:getitem_color_key",
|
353 |
+
),
|
354 |
+
pytest.param(
|
355 |
+
Expected(
|
356 |
+
create=lambda: create_readonly({"foo1": "bar"}),
|
357 |
+
op=lambda cfg: cfg.merge_with({"foo2": "bar"}),
|
358 |
+
exception_type=ReadonlyConfigError,
|
359 |
+
key="foo2",
|
360 |
+
msg="Cannot change read-only config container",
|
361 |
+
),
|
362 |
+
id="dict,readonly:merge_with",
|
363 |
+
),
|
364 |
+
pytest.param(
|
365 |
+
Expected(
|
366 |
+
create=lambda: OmegaConf.structured(ConcretePlugin),
|
367 |
+
op=lambda cfg: OmegaConf.merge(cfg, {"params": {"foo": "bar"}}),
|
368 |
+
exception_type=ValidationError,
|
369 |
+
msg="Value 'bar' could not be converted to Integer",
|
370 |
+
key="foo",
|
371 |
+
full_key="params.foo",
|
372 |
+
object_type=ConcretePlugin.FoobarParams,
|
373 |
+
child_node=lambda cfg: cfg.params.foo,
|
374 |
+
parent_node=lambda cfg: cfg.params,
|
375 |
+
),
|
376 |
+
id="structured:merge,invalid_field_type",
|
377 |
+
),
|
378 |
+
pytest.param(
|
379 |
+
Expected(
|
380 |
+
create=lambda: OmegaConf.structured(ConcretePlugin),
|
381 |
+
op=lambda cfg: OmegaConf.merge(cfg, {"params": {"zlonk": 10}}),
|
382 |
+
exception_type=ConfigKeyError,
|
383 |
+
msg="Key 'zlonk' not in 'FoobarParams'",
|
384 |
+
key="zlonk",
|
385 |
+
full_key="params.zlonk",
|
386 |
+
object_type=ConcretePlugin.FoobarParams,
|
387 |
+
parent_node=lambda cfg: cfg.params,
|
388 |
+
),
|
389 |
+
id="structured:merge,adding_an_invalid_key",
|
390 |
+
),
|
391 |
+
pytest.param(
|
392 |
+
Expected(
|
393 |
+
create=lambda: OmegaConf.structured(Package),
|
394 |
+
op=lambda cfg: OmegaConf.merge(cfg, {"modules": [{"foo": "var"}]}),
|
395 |
+
exception_type=ConfigKeyError,
|
396 |
+
msg="Key 'foo' not in 'Module'",
|
397 |
+
key="foo",
|
398 |
+
full_key="modules[0].foo",
|
399 |
+
object_type=Module,
|
400 |
+
low_level=True,
|
401 |
+
),
|
402 |
+
id="structured:merge,bad_key_merge",
|
403 |
+
),
|
404 |
+
# merge_with
|
405 |
+
pytest.param(
|
406 |
+
Expected(
|
407 |
+
create=lambda: OmegaConf.structured(ConcretePlugin),
|
408 |
+
op=lambda cfg: cfg.merge_with(Plugin),
|
409 |
+
exception_type=ValidationError,
|
410 |
+
msg="Plugin is not a subclass of ConcretePlugin. value: {'name': '???', 'params': '???'}",
|
411 |
+
object_type=ConcretePlugin,
|
412 |
+
),
|
413 |
+
id="structured:merge_invalid_dataclass",
|
414 |
+
),
|
415 |
+
# get
|
416 |
+
pytest.param(
|
417 |
+
Expected(
|
418 |
+
create=lambda: OmegaConf.create(),
|
419 |
+
op=lambda cfg: cfg.get(IllegalType),
|
420 |
+
exception_type=KeyValidationError,
|
421 |
+
msg="Incompatible key type 'type'",
|
422 |
+
key=IllegalType,
|
423 |
+
full_key="",
|
424 |
+
),
|
425 |
+
id="dict:get_illegal_type",
|
426 |
+
),
|
427 |
+
pytest.param(
|
428 |
+
Expected(
|
429 |
+
create=lambda: OmegaConf.create(),
|
430 |
+
op=lambda cfg: cfg.get(IllegalType()),
|
431 |
+
exception_type=KeyValidationError,
|
432 |
+
msg="Incompatible key type 'IllegalType'",
|
433 |
+
key=IllegalType(),
|
434 |
+
),
|
435 |
+
id="dict:get_object_of_illegal_type",
|
436 |
+
),
|
437 |
+
# dict:create
|
438 |
+
pytest.param(
|
439 |
+
Expected(
|
440 |
+
create=lambda: None,
|
441 |
+
op=lambda cfg: OmegaConf.structured(NotOptionalInt),
|
442 |
+
exception_type=ValidationError,
|
443 |
+
msg="Non optional field cannot be assigned None",
|
444 |
+
object_type_str=None,
|
445 |
+
ref_type_str=None,
|
446 |
+
),
|
447 |
+
id="dict:create_none_optional_with_none",
|
448 |
+
),
|
449 |
+
pytest.param(
|
450 |
+
Expected(
|
451 |
+
create=lambda: None,
|
452 |
+
op=lambda cfg: OmegaConf.structured(NotOptionalInt),
|
453 |
+
exception_type=ValidationError,
|
454 |
+
object_type=None,
|
455 |
+
msg="Non optional field cannot be assigned None",
|
456 |
+
object_type_str="NotOptionalInt",
|
457 |
+
ref_type_str=None,
|
458 |
+
),
|
459 |
+
id="dict:create:not_optional_int_field_with_none",
|
460 |
+
),
|
461 |
+
pytest.param(
|
462 |
+
Expected(
|
463 |
+
create=lambda: None,
|
464 |
+
op=lambda cfg: OmegaConf.structured(NotOptionalA),
|
465 |
+
exception_type=ValidationError,
|
466 |
+
object_type=None,
|
467 |
+
key=None,
|
468 |
+
full_key="x",
|
469 |
+
msg="field 'x' is not Optional",
|
470 |
+
object_type_str="NotOptionalInt",
|
471 |
+
ref_type_str=None,
|
472 |
+
),
|
473 |
+
id="dict:create:not_optional_A_field_with_none",
|
474 |
+
),
|
475 |
+
pytest.param(
|
476 |
+
Expected(
|
477 |
+
create=lambda: None,
|
478 |
+
op=lambda cfg: OmegaConf.structured(IllegalType),
|
479 |
+
exception_type=ValidationError,
|
480 |
+
msg="Input class 'IllegalType' is not a structured config. did you forget to decorate it as a dataclass?",
|
481 |
+
object_type_str=None,
|
482 |
+
ref_type_str=None,
|
483 |
+
),
|
484 |
+
id="dict_create_from_illegal_type",
|
485 |
+
),
|
486 |
+
pytest.param(
|
487 |
+
Expected(
|
488 |
+
create=lambda: None,
|
489 |
+
op=lambda cfg: OmegaConf.structured(IllegalType()),
|
490 |
+
exception_type=ValidationError,
|
491 |
+
msg="Object of unsupported type: 'IllegalType'",
|
492 |
+
object_type_str=None,
|
493 |
+
ref_type_str=None,
|
494 |
+
),
|
495 |
+
id="structured:create_from_unsupported_object",
|
496 |
+
),
|
497 |
+
pytest.param(
|
498 |
+
Expected(
|
499 |
+
create=lambda: None,
|
500 |
+
op=lambda cfg: OmegaConf.structured(UnionError),
|
501 |
+
exception_type=ValueError,
|
502 |
+
msg="Union types are not supported:\nx: Union[int, str]",
|
503 |
+
object_type_str=None,
|
504 |
+
ref_type_str=None,
|
505 |
+
num_lines=4,
|
506 |
+
),
|
507 |
+
id="structured:create_with_union_error",
|
508 |
+
),
|
509 |
+
# assign
|
510 |
+
pytest.param(
|
511 |
+
Expected(
|
512 |
+
create=lambda: DictConfig(ref_type=ConcretePlugin, content="???"),
|
513 |
+
op=lambda cfg: cfg._set_value(1),
|
514 |
+
exception_type=ValidationError,
|
515 |
+
msg="Invalid type assigned : int is not a subclass of ConcretePlugin. value: 1",
|
516 |
+
low_level=True,
|
517 |
+
ref_type=Optional[ConcretePlugin],
|
518 |
+
),
|
519 |
+
id="dict:set_value:reftype_mismatch",
|
520 |
+
),
|
521 |
+
pytest.param(
|
522 |
+
Expected(
|
523 |
+
create=lambda: DictConfig(
|
524 |
+
key_type=str, element_type=int, content={"foo": 10, "bar": 20}
|
525 |
+
),
|
526 |
+
op=lambda cfg: cfg.__setitem__("baz", "fail"),
|
527 |
+
exception_type=ValidationError,
|
528 |
+
msg="Value 'fail' could not be converted to Integer",
|
529 |
+
key="baz",
|
530 |
+
ref_type=Optional[Dict[str, int]],
|
531 |
+
),
|
532 |
+
id="DictConfig[str,int]:assigned_str_value",
|
533 |
+
),
|
534 |
+
# delete
|
535 |
+
pytest.param(
|
536 |
+
Expected(
|
537 |
+
create=lambda: create_readonly({"foo": "bar"}),
|
538 |
+
op=lambda cfg: cfg.__delitem__("foo"),
|
539 |
+
exception_type=ReadonlyConfigError,
|
540 |
+
msg="DictConfig in read-only mode does not support deletion",
|
541 |
+
key="foo",
|
542 |
+
child_node=lambda cfg: cfg.foo,
|
543 |
+
),
|
544 |
+
id="dict,readonly:del",
|
545 |
+
),
|
546 |
+
pytest.param(
|
547 |
+
Expected(
|
548 |
+
create=lambda: create_struct({"foo": "bar"}),
|
549 |
+
op=lambda cfg: cfg.__delitem__("foo"),
|
550 |
+
exception_type=ConfigTypeError,
|
551 |
+
msg="DictConfig in struct mode does not support deletion",
|
552 |
+
key="foo",
|
553 |
+
child_node=lambda cfg: cfg.foo,
|
554 |
+
),
|
555 |
+
id="dict,struct:del",
|
556 |
+
),
|
557 |
+
pytest.param(
|
558 |
+
Expected(
|
559 |
+
create=lambda: OmegaConf.structured(User(name="bond")),
|
560 |
+
op=lambda cfg: cfg.__delitem__("name"),
|
561 |
+
exception_type=ConfigTypeError,
|
562 |
+
msg="User (DictConfig) does not support deletion",
|
563 |
+
object_type=User,
|
564 |
+
key="name",
|
565 |
+
child_node=lambda cfg: cfg.name,
|
566 |
+
),
|
567 |
+
id="dict,structured:del",
|
568 |
+
),
|
569 |
+
##############
|
570 |
+
# ListConfig #
|
571 |
+
##############
|
572 |
+
# getattr
|
573 |
+
pytest.param(
|
574 |
+
Expected(
|
575 |
+
create=lambda: OmegaConf.create([1, 2, 3]),
|
576 |
+
op=lambda cfg: setattr(cfg, "foo", 10),
|
577 |
+
exception_type=ConfigAttributeError,
|
578 |
+
key="foo",
|
579 |
+
full_key="[foo]",
|
580 |
+
msg="ListConfig does not support attribute access",
|
581 |
+
),
|
582 |
+
id="list:setattr",
|
583 |
+
),
|
584 |
+
# setattr
|
585 |
+
pytest.param(
|
586 |
+
Expected(
|
587 |
+
create=lambda: OmegaConf.create([1, 2, 3]),
|
588 |
+
op=lambda cfg: getattr(cfg, "foo"),
|
589 |
+
exception_type=ConfigAttributeError,
|
590 |
+
key="foo",
|
591 |
+
full_key="[foo]",
|
592 |
+
msg="ListConfig does not support attribute access",
|
593 |
+
),
|
594 |
+
id="list:setattr",
|
595 |
+
),
|
596 |
+
# get node
|
597 |
+
pytest.param(
|
598 |
+
Expected(
|
599 |
+
create=lambda: OmegaConf.create([1, 2, 3]),
|
600 |
+
op=lambda cfg: cfg._get_node("foo"),
|
601 |
+
exception_type=KeyValidationError,
|
602 |
+
key="foo",
|
603 |
+
full_key="[foo]",
|
604 |
+
msg="ListConfig indices must be integers or slices, not str",
|
605 |
+
ref_type=Optional[List[Any]],
|
606 |
+
),
|
607 |
+
id="list:get_nox_ex:invalid_index_type",
|
608 |
+
),
|
609 |
+
pytest.param(
|
610 |
+
Expected(
|
611 |
+
create=lambda: OmegaConf.create([1, 2, 3]),
|
612 |
+
op=lambda cfg: cfg._get_node(20),
|
613 |
+
exception_type=IndexError,
|
614 |
+
msg="list index out of range",
|
615 |
+
key=20,
|
616 |
+
full_key="[20]",
|
617 |
+
),
|
618 |
+
id="list:get_node_ex:index_out_of_range",
|
619 |
+
),
|
620 |
+
pytest.param(
|
621 |
+
Expected(
|
622 |
+
create=lambda: ListConfig(content=None),
|
623 |
+
op=lambda cfg: cfg._get_node(20),
|
624 |
+
exception_type=TypeError,
|
625 |
+
msg="Cannot get_node from a ListConfig object representing None",
|
626 |
+
key=20,
|
627 |
+
full_key="[20]",
|
628 |
+
ref_type=Optional[List[Any]],
|
629 |
+
),
|
630 |
+
id="list:get_node_none",
|
631 |
+
),
|
632 |
+
pytest.param(
|
633 |
+
Expected(
|
634 |
+
create=lambda: ListConfig(content="???"),
|
635 |
+
op=lambda cfg: cfg._get_node(20),
|
636 |
+
exception_type=MissingMandatoryValue,
|
637 |
+
msg="Cannot get_node from a missing ListConfig",
|
638 |
+
key=20,
|
639 |
+
full_key="[20]",
|
640 |
+
),
|
641 |
+
id="list:get_node_missing",
|
642 |
+
),
|
643 |
+
# list:create
|
644 |
+
pytest.param(
|
645 |
+
Expected(
|
646 |
+
create=lambda: None,
|
647 |
+
op=lambda cfg: ListConfig(is_optional=False, content=None),
|
648 |
+
exception_type=ValidationError,
|
649 |
+
object_type=None,
|
650 |
+
msg="Non optional ListConfig cannot be constructed from None",
|
651 |
+
object_type_str=None,
|
652 |
+
ref_type_str=None,
|
653 |
+
),
|
654 |
+
id="list:create:not_optional_with_none",
|
655 |
+
),
|
656 |
+
# append
|
657 |
+
pytest.param(
|
658 |
+
Expected(
|
659 |
+
create=lambda: OmegaConf.create([]),
|
660 |
+
op=lambda cfg: cfg.append(IllegalType()),
|
661 |
+
exception_type=UnsupportedValueType,
|
662 |
+
msg="Value 'IllegalType' is not a supported primitive type",
|
663 |
+
key=0,
|
664 |
+
full_key="[0]",
|
665 |
+
),
|
666 |
+
id="list:append_value_of_illegal_type",
|
667 |
+
),
|
668 |
+
# pop
|
669 |
+
pytest.param(
|
670 |
+
Expected(
|
671 |
+
create=lambda: create_readonly([1, 2, 3]),
|
672 |
+
op=lambda cfg: cfg.pop(0),
|
673 |
+
exception_type=ReadonlyConfigError,
|
674 |
+
msg="Cannot pop from read-only ListConfig",
|
675 |
+
key=0,
|
676 |
+
full_key="[0]",
|
677 |
+
child_node=lambda cfg: cfg[0],
|
678 |
+
),
|
679 |
+
id="list:readonly:pop",
|
680 |
+
),
|
681 |
+
pytest.param(
|
682 |
+
Expected(
|
683 |
+
create=lambda: OmegaConf.create([1, 2, 3]),
|
684 |
+
op=lambda cfg: cfg.pop("Invalid_key_type"),
|
685 |
+
exception_type=ConfigTypeError,
|
686 |
+
msg="ListConfig indices must be integers or slices, not str",
|
687 |
+
key="Invalid_key_type",
|
688 |
+
full_key="[Invalid_key_type]",
|
689 |
+
),
|
690 |
+
id="list:pop_invalid_key",
|
691 |
+
),
|
692 |
+
pytest.param(
|
693 |
+
Expected(
|
694 |
+
create=lambda: create_struct({"foo": "bar"}),
|
695 |
+
op=lambda cfg: cfg.pop("foo"),
|
696 |
+
exception_type=ConfigTypeError,
|
697 |
+
msg="DictConfig in struct mode does not support pop",
|
698 |
+
key="foo",
|
699 |
+
child_node=lambda cfg: cfg.foo,
|
700 |
+
),
|
701 |
+
id="dict,struct:pop",
|
702 |
+
),
|
703 |
+
pytest.param(
|
704 |
+
Expected(
|
705 |
+
create=lambda: OmegaConf.structured(ConcretePlugin),
|
706 |
+
op=lambda cfg: cfg.pop("name"),
|
707 |
+
exception_type=ConfigTypeError,
|
708 |
+
msg="ConcretePlugin (DictConfig) does not support pop",
|
709 |
+
key="name",
|
710 |
+
child_node=lambda cfg: cfg.name,
|
711 |
+
),
|
712 |
+
id="dict,structured:pop",
|
713 |
+
),
|
714 |
+
pytest.param(
|
715 |
+
Expected(
|
716 |
+
create=lambda: ListConfig(content=None),
|
717 |
+
op=lambda cfg: cfg.pop(0),
|
718 |
+
exception_type=TypeError,
|
719 |
+
msg="Cannot pop from a ListConfig object representing None",
|
720 |
+
key=0,
|
721 |
+
full_key="[0]",
|
722 |
+
),
|
723 |
+
id="list:pop_from_none",
|
724 |
+
),
|
725 |
+
pytest.param(
|
726 |
+
Expected(
|
727 |
+
create=lambda: ListConfig(content="???"),
|
728 |
+
op=lambda cfg: cfg.pop(0),
|
729 |
+
exception_type=MissingMandatoryValue,
|
730 |
+
msg="Cannot pop from a missing ListConfig",
|
731 |
+
key=0,
|
732 |
+
full_key="[0]",
|
733 |
+
),
|
734 |
+
id="list:pop_from_missing",
|
735 |
+
),
|
736 |
+
# getitem
|
737 |
+
pytest.param(
|
738 |
+
Expected(
|
739 |
+
create=lambda: OmegaConf.create(["???"]),
|
740 |
+
op=lambda cfg: cfg.__getitem__(slice(0, 1)),
|
741 |
+
exception_type=MissingMandatoryValue,
|
742 |
+
msg="Missing mandatory value: [0:1]",
|
743 |
+
key=slice(0, 1),
|
744 |
+
full_key="[0:1]",
|
745 |
+
child_node=lambda cfg: cfg._get_node(slice(0, 1)),
|
746 |
+
),
|
747 |
+
id="list:subscript_slice_with_missing",
|
748 |
+
),
|
749 |
+
pytest.param(
|
750 |
+
Expected(
|
751 |
+
create=lambda: OmegaConf.create([10, "???"]),
|
752 |
+
op=lambda cfg: cfg.__getitem__(1),
|
753 |
+
exception_type=MissingMandatoryValue,
|
754 |
+
msg="Missing mandatory value: [1]",
|
755 |
+
key=1,
|
756 |
+
full_key="[1]",
|
757 |
+
child_node=lambda cfg: cfg._get_node(1),
|
758 |
+
),
|
759 |
+
id="list:subscript_index_with_missing",
|
760 |
+
),
|
761 |
+
pytest.param(
|
762 |
+
Expected(
|
763 |
+
create=lambda: OmegaConf.create([1, 2, 3]),
|
764 |
+
op=lambda cfg: cfg.__getitem__(20),
|
765 |
+
exception_type=IndexError,
|
766 |
+
msg="list index out of range",
|
767 |
+
key=20,
|
768 |
+
full_key="[20]",
|
769 |
+
),
|
770 |
+
id="list:subscript:index_out_of_range",
|
771 |
+
),
|
772 |
+
pytest.param(
|
773 |
+
Expected(
|
774 |
+
create=lambda: OmegaConf.create([1, 2, 3]),
|
775 |
+
op=lambda cfg: cfg.__getitem__("foo"),
|
776 |
+
exception_type=KeyValidationError,
|
777 |
+
msg="ListConfig indices must be integers or slices, not str",
|
778 |
+
key="foo",
|
779 |
+
full_key="[foo]",
|
780 |
+
),
|
781 |
+
id="list:getitem,illegal_key_type",
|
782 |
+
),
|
783 |
+
pytest.param(
|
784 |
+
Expected(
|
785 |
+
create=lambda: ListConfig(content=None),
|
786 |
+
op=lambda cfg: cfg.__getitem__(0),
|
787 |
+
exception_type=TypeError,
|
788 |
+
msg="ListConfig object representing None is not subscriptable",
|
789 |
+
key=0,
|
790 |
+
full_key="[0]",
|
791 |
+
),
|
792 |
+
id="list:getitem,illegal_key_type",
|
793 |
+
),
|
794 |
+
# setitem
|
795 |
+
pytest.param(
|
796 |
+
Expected(
|
797 |
+
create=lambda: OmegaConf.create([None]),
|
798 |
+
op=lambda cfg: cfg.__setitem__(0, IllegalType()),
|
799 |
+
exception_type=UnsupportedValueType,
|
800 |
+
msg="Value 'IllegalType' is not a supported primitive type",
|
801 |
+
key=0,
|
802 |
+
full_key="[0]",
|
803 |
+
),
|
804 |
+
id="list:setitem,illegal_value_type",
|
805 |
+
),
|
806 |
+
pytest.param(
|
807 |
+
Expected(
|
808 |
+
create=lambda: OmegaConf.create([1, 2, 3]),
|
809 |
+
op=lambda cfg: cfg.__setitem__("foo", 4),
|
810 |
+
exception_type=KeyValidationError,
|
811 |
+
msg="ListConfig indices must be integers or slices, not str",
|
812 |
+
key="foo",
|
813 |
+
full_key="[foo]",
|
814 |
+
),
|
815 |
+
id="list:setitem,illegal_key_type",
|
816 |
+
),
|
817 |
+
pytest.param(
|
818 |
+
Expected(
|
819 |
+
create=lambda: create_readonly([1, 2, 3]),
|
820 |
+
op=lambda cfg: cfg.__setitem__(0, 4),
|
821 |
+
exception_type=ReadonlyConfigError,
|
822 |
+
msg="ListConfig is read-only",
|
823 |
+
key=0,
|
824 |
+
full_key="[0]",
|
825 |
+
child_node=lambda cfg: cfg[0],
|
826 |
+
),
|
827 |
+
id="list,readonly:setitem",
|
828 |
+
),
|
829 |
+
# _set_value
|
830 |
+
pytest.param(
|
831 |
+
Expected(
|
832 |
+
create=lambda: ListConfig(is_optional=False, element_type=int, content=[]),
|
833 |
+
op=lambda cfg: cfg._set_value(None),
|
834 |
+
exception_type=ValidationError,
|
835 |
+
object_type=None,
|
836 |
+
msg="Non optional ListConfig cannot be constructed from None",
|
837 |
+
ref_type=List[int],
|
838 |
+
low_level=True,
|
839 |
+
),
|
840 |
+
id="list:create_not_optional:_set_value(None)",
|
841 |
+
),
|
842 |
+
pytest.param(
|
843 |
+
Expected(
|
844 |
+
create=lambda: ListConfig(content=[1, 2]),
|
845 |
+
op=lambda cfg: cfg._set_value(True),
|
846 |
+
exception_type=ValidationError,
|
847 |
+
object_type=None,
|
848 |
+
msg="Invalid value assigned : bool is not a subclass of ListConfig or list",
|
849 |
+
ref_type=List[int],
|
850 |
+
low_level=True,
|
851 |
+
),
|
852 |
+
id="list:create_not_optional:_set_value(True)",
|
853 |
+
),
|
854 |
+
# assign
|
855 |
+
pytest.param(
|
856 |
+
Expected(
|
857 |
+
create=lambda: ListConfig(element_type=int, content=[1, 2, 3]),
|
858 |
+
op=lambda cfg: cfg.__setitem__(0, "foo"),
|
859 |
+
exception_type=ValidationError,
|
860 |
+
msg="Value 'foo' could not be converted to Integer",
|
861 |
+
key=0,
|
862 |
+
full_key="[0]",
|
863 |
+
child_node=lambda cfg: cfg[0],
|
864 |
+
ref_type=Optional[List[int]],
|
865 |
+
),
|
866 |
+
id="list,int_elements:assigned_str_element",
|
867 |
+
),
|
868 |
+
pytest.param(
|
869 |
+
Expected(
|
870 |
+
# make sure OmegaConf.create is not losing critical metadata.
|
871 |
+
create=lambda: OmegaConf.create(
|
872 |
+
ListConfig(element_type=int, content=[1, 2, 3])
|
873 |
+
),
|
874 |
+
op=lambda cfg: cfg.__setitem__(0, "foo"),
|
875 |
+
exception_type=ValidationError,
|
876 |
+
msg="Value 'foo' could not be converted to Integer",
|
877 |
+
key=0,
|
878 |
+
full_key="[0]",
|
879 |
+
child_node=lambda cfg: cfg[0],
|
880 |
+
ref_type=Optional[List[int]],
|
881 |
+
),
|
882 |
+
id="list,int_elements:assigned_str_element",
|
883 |
+
),
|
884 |
+
pytest.param(
|
885 |
+
Expected(
|
886 |
+
create=lambda: OmegaConf.create(
|
887 |
+
[IntegerNode(is_optional=False, value=0), 2, 3]
|
888 |
+
),
|
889 |
+
op=lambda cfg: cfg.__setitem__(0, None),
|
890 |
+
exception_type=ValidationError,
|
891 |
+
msg="[0] is not optional and cannot be assigned None",
|
892 |
+
key=0,
|
893 |
+
full_key="[0]",
|
894 |
+
child_node=lambda cfg: cfg[0],
|
895 |
+
ref_type=Optional[List[Any]],
|
896 |
+
),
|
897 |
+
id="list,not_optional:null_assignment",
|
898 |
+
),
|
899 |
+
# index
|
900 |
+
pytest.param(
|
901 |
+
Expected(
|
902 |
+
create=lambda: create_readonly([1, 2, 3]),
|
903 |
+
op=lambda cfg: cfg.index(99),
|
904 |
+
exception_type=ConfigValueError,
|
905 |
+
msg="Item not found in ListConfig",
|
906 |
+
),
|
907 |
+
id="list,readonly:index_not_found",
|
908 |
+
),
|
909 |
+
# insert
|
910 |
+
pytest.param(
|
911 |
+
Expected(
|
912 |
+
create=lambda: create_readonly([1, 2, 3]),
|
913 |
+
op=lambda cfg: cfg.insert(1, 99),
|
914 |
+
exception_type=ReadonlyConfigError,
|
915 |
+
msg="Cannot insert into a read-only ListConfig",
|
916 |
+
key=1,
|
917 |
+
full_key="[1]",
|
918 |
+
child_node=lambda cfg: cfg[1],
|
919 |
+
),
|
920 |
+
id="list,readonly:insert",
|
921 |
+
),
|
922 |
+
pytest.param(
|
923 |
+
Expected(
|
924 |
+
create=lambda: ListConfig(content=None),
|
925 |
+
op=lambda cfg: cfg.insert(1, 99),
|
926 |
+
exception_type=ConfigTypeError,
|
927 |
+
msg="Cannot insert into ListConfig object representing None",
|
928 |
+
key=1,
|
929 |
+
full_key="[1]",
|
930 |
+
),
|
931 |
+
id="list:insert_into_none",
|
932 |
+
),
|
933 |
+
pytest.param(
|
934 |
+
Expected(
|
935 |
+
create=lambda: ListConfig(content="???"),
|
936 |
+
op=lambda cfg: cfg.insert(1, 99),
|
937 |
+
exception_type=MissingMandatoryValue,
|
938 |
+
msg="Cannot insert into missing ListConfig",
|
939 |
+
key=1,
|
940 |
+
full_key="[1]",
|
941 |
+
child_node=lambda _cfg: None,
|
942 |
+
ref_type=Optional[List[Any]],
|
943 |
+
),
|
944 |
+
id="list:insert_into_missing",
|
945 |
+
),
|
946 |
+
# get
|
947 |
+
pytest.param(
|
948 |
+
Expected(
|
949 |
+
create=lambda: ListConfig(content=None),
|
950 |
+
op=lambda cfg: cfg.get(0),
|
951 |
+
exception_type=TypeError,
|
952 |
+
msg="Cannot get from a ListConfig object representing None",
|
953 |
+
key=0,
|
954 |
+
full_key="[0]",
|
955 |
+
ref_type=Optional[List[Any]],
|
956 |
+
),
|
957 |
+
id="list:get_from_none",
|
958 |
+
),
|
959 |
+
pytest.param(
|
960 |
+
Expected(
|
961 |
+
create=lambda: ListConfig(content="???"),
|
962 |
+
op=lambda cfg: cfg.get(0),
|
963 |
+
exception_type=MissingMandatoryValue,
|
964 |
+
msg="Cannot get from a missing ListConfig",
|
965 |
+
key=0,
|
966 |
+
full_key="[0]",
|
967 |
+
),
|
968 |
+
id="list:get_from_missing",
|
969 |
+
),
|
970 |
+
# sort
|
971 |
+
pytest.param(
|
972 |
+
Expected(
|
973 |
+
create=lambda: create_readonly([1, 2, 3]),
|
974 |
+
op=lambda cfg: cfg.sort(),
|
975 |
+
exception_type=ReadonlyConfigError,
|
976 |
+
msg="Cannot sort a read-only ListConfig",
|
977 |
+
),
|
978 |
+
id="list:readonly:sort",
|
979 |
+
),
|
980 |
+
pytest.param(
|
981 |
+
Expected(
|
982 |
+
create=lambda: ListConfig(content=None),
|
983 |
+
op=lambda cfg: cfg.sort(),
|
984 |
+
exception_type=TypeError,
|
985 |
+
msg="Cannot sort a ListConfig object representing None",
|
986 |
+
),
|
987 |
+
id="list:sort_from_none",
|
988 |
+
),
|
989 |
+
pytest.param(
|
990 |
+
Expected(
|
991 |
+
create=lambda: ListConfig(content="???"),
|
992 |
+
op=lambda cfg: cfg.sort(),
|
993 |
+
exception_type=MissingMandatoryValue,
|
994 |
+
msg="Cannot sort a missing ListConfig",
|
995 |
+
),
|
996 |
+
id="list:sort_from_missing",
|
997 |
+
),
|
998 |
+
# # iter
|
999 |
+
pytest.param(
|
1000 |
+
Expected(
|
1001 |
+
create=lambda: create_readonly([1, 2, 3]),
|
1002 |
+
op=lambda cfg: cfg.sort(),
|
1003 |
+
exception_type=ReadonlyConfigError,
|
1004 |
+
msg="Cannot sort a read-only ListConfig",
|
1005 |
+
),
|
1006 |
+
id="list:readonly:sort",
|
1007 |
+
),
|
1008 |
+
pytest.param(
|
1009 |
+
Expected(
|
1010 |
+
create=lambda: ListConfig(content=None),
|
1011 |
+
op=lambda cfg: iter(cfg),
|
1012 |
+
exception_type=TypeError,
|
1013 |
+
msg="Cannot iterate a ListConfig object representing None",
|
1014 |
+
),
|
1015 |
+
id="list:iter_none",
|
1016 |
+
),
|
1017 |
+
pytest.param(
|
1018 |
+
Expected(
|
1019 |
+
create=lambda: ListConfig(content="???"),
|
1020 |
+
op=lambda cfg: iter(cfg),
|
1021 |
+
exception_type=MissingMandatoryValue,
|
1022 |
+
msg="Cannot iterate a missing ListConfig",
|
1023 |
+
),
|
1024 |
+
id="list:iter_missing",
|
1025 |
+
),
|
1026 |
+
# delete
|
1027 |
+
pytest.param(
|
1028 |
+
Expected(
|
1029 |
+
create=lambda: create_readonly([1, 2, 3]),
|
1030 |
+
op=lambda cfg: cfg.__delitem__(0),
|
1031 |
+
exception_type=ReadonlyConfigError,
|
1032 |
+
msg="Cannot delete item from read-only ListConfig",
|
1033 |
+
key=0,
|
1034 |
+
full_key="[0]",
|
1035 |
+
child_node=lambda cfg: cfg._get_node(0),
|
1036 |
+
),
|
1037 |
+
id="list,readonly:del",
|
1038 |
+
),
|
1039 |
+
]
|
1040 |
+
|
1041 |
+
|
1042 |
+
def create_struct(cfg: Any) -> Any:
|
1043 |
+
cfg = OmegaConf.create(cfg)
|
1044 |
+
OmegaConf.set_struct(cfg, True)
|
1045 |
+
return cfg
|
1046 |
+
|
1047 |
+
|
1048 |
+
def create_readonly(cfg: Any) -> Any:
|
1049 |
+
cfg = OmegaConf.create(cfg)
|
1050 |
+
OmegaConf.set_readonly(cfg, True)
|
1051 |
+
return cfg
|
1052 |
+
|
1053 |
+
|
1054 |
+
@pytest.mark.parametrize( # type:ignore
|
1055 |
+
"expected", params
|
1056 |
+
)
|
1057 |
+
def test_errors(expected: Expected, monkeypatch: Any) -> None:
|
1058 |
+
monkeypatch.setenv("OC_CAUSE", "0")
|
1059 |
+
cfg = expected.create()
|
1060 |
+
expected.finalize(cfg)
|
1061 |
+
msg = expected.msg
|
1062 |
+
with pytest.raises(expected.exception_type, match=re.escape(msg)) as einfo:
|
1063 |
+
try:
|
1064 |
+
expected.op(cfg)
|
1065 |
+
except Exception as e:
|
1066 |
+
# helps in debugging
|
1067 |
+
raise e
|
1068 |
+
ex = einfo.value
|
1069 |
+
|
1070 |
+
assert ex.object_type == expected.object_type
|
1071 |
+
assert ex.key == expected.key
|
1072 |
+
if not expected.low_level:
|
1073 |
+
if isinstance(ex, OmegaConfBaseException):
|
1074 |
+
assert str(ex).count("\n") == expected.num_lines
|
1075 |
+
assert ex.parent_node == expected.parent_node(cfg)
|
1076 |
+
assert ex.child_node == expected.child_node(cfg)
|
1077 |
+
assert ex.full_key == expected.full_key
|
1078 |
+
assert isinstance(expected.full_key, str)
|
1079 |
+
|
1080 |
+
if expected.ref_type is not None:
|
1081 |
+
assert ex.ref_type == expected.ref_type
|
1082 |
+
|
1083 |
+
if expected.object_type is not None:
|
1084 |
+
assert ex.object_type == expected.object_type
|
1085 |
+
|
1086 |
+
with monkeypatch.context() as m:
|
1087 |
+
m.setenv("OC_CAUSE", "1")
|
1088 |
+
try:
|
1089 |
+
expected.op(cfg)
|
1090 |
+
except Exception as e:
|
1091 |
+
assert e.__cause__ is not None
|
1092 |
+
|
1093 |
+
with monkeypatch.context() as m:
|
1094 |
+
m.setenv("OC_CAUSE", "0")
|
1095 |
+
try:
|
1096 |
+
expected.op(cfg)
|
1097 |
+
except Exception as e:
|
1098 |
+
assert e.__cause__ is None
|
tests/test_get_full_key.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
|
5 |
+
from omegaconf import DictConfig, IntegerNode, OmegaConf
|
6 |
+
|
7 |
+
from . import Color
|
8 |
+
|
9 |
+
|
10 |
+
@pytest.mark.parametrize( # type: ignore
|
11 |
+
"cfg, select, key, expected",
|
12 |
+
[
|
13 |
+
({}, "", "a", "a"),
|
14 |
+
# 1
|
15 |
+
# dict
|
16 |
+
({"a": 1}, "", "a", "a"),
|
17 |
+
({"a": 1}, "", "bad", "bad"),
|
18 |
+
# dict empty key
|
19 |
+
({"a": 1}, "", "", ""),
|
20 |
+
({"a": 1}, "", "bad", "bad"),
|
21 |
+
# list
|
22 |
+
([1, 2, 3], "", "2", "[2]"),
|
23 |
+
([1, 2, 3], "", "999", "[999]"),
|
24 |
+
# list empty key
|
25 |
+
([1, 2, 3], "", "", ""),
|
26 |
+
([1, 2, 3], "", "999", "[999]"),
|
27 |
+
# 2
|
28 |
+
# dd
|
29 |
+
({"a": 1, "b": {"c": 1}}, "b", "c", "b.c"),
|
30 |
+
({"a": 1, "b": {"c": 1}}, "b", "bad", "b.bad"),
|
31 |
+
# dl
|
32 |
+
({"a": [1, 2, 3]}, "a", 1, "a[1]"),
|
33 |
+
({"a": [1, 2, 3]}, "a", 999, "a[999]"),
|
34 |
+
# ll
|
35 |
+
([[1, 2, 3]], "0", "2", "[0][2]"),
|
36 |
+
([[1, 2, 3]], "0", "999", "[0][999]"),
|
37 |
+
# ld
|
38 |
+
([1, 2, {"a": 1}], "2", "a", "[2].a"),
|
39 |
+
([1, 2, {"a": 1}], "2", "bad", "[2].bad"),
|
40 |
+
# dd empty key
|
41 |
+
({"a": 1, "b": {"c": 1}}, "b", "", "b"),
|
42 |
+
({"a": 1, "b": {"c": 1}}, "b", "bad", "b.bad"),
|
43 |
+
# 3
|
44 |
+
# ddd
|
45 |
+
({"a": {"b": {"c": 1}}}, "a.b", "c", "a.b.c"),
|
46 |
+
({"a": {"b": {"c": 1}}}, "a.b", "bad", "a.b.bad"),
|
47 |
+
# ddl
|
48 |
+
({"a": {"b": [0, 1]}}, "a.b", 0, "a.b[0]"),
|
49 |
+
({"a": {"b": [0, 1]}}, "a.b", 999, "a.b[999]"),
|
50 |
+
# dll
|
51 |
+
({"a": [1, [2]]}, "a.1", 0, "a[1][0]"),
|
52 |
+
({"a": [1, [2]]}, "a.1", 999, "a[1][999]"),
|
53 |
+
# dld
|
54 |
+
({"a": [{"b": 2}]}, "a.0", "b", "a[0].b"),
|
55 |
+
({"a": [{"b": 2}]}, "a.0", "bad", "a[0].bad"),
|
56 |
+
# ldd
|
57 |
+
([{"a": {"b": 1}}], "0.a", "b", "[0].a.b"),
|
58 |
+
([{"a": {"b": 1}}], "0.a", "bad", "[0].a.bad"),
|
59 |
+
# ldl
|
60 |
+
([{"a": [0]}], "0.a", 0, "[0].a[0]"),
|
61 |
+
([{"a": [0]}], "0.a", 999, "[0].a[999]"),
|
62 |
+
# lld
|
63 |
+
([[{"a": 1}]], "0.0", "a", "[0][0].a"),
|
64 |
+
([[{"a": 1}]], "0.0", "bad", "[0][0].bad"),
|
65 |
+
# lll
|
66 |
+
([[[0]]], "0.0", 0, "[0][0][0]"),
|
67 |
+
# lldddl
|
68 |
+
([[{"a": {"a": [0]}}]], "0.0.a.a", 0, "[0][0].a.a[0]"),
|
69 |
+
# special cases
|
70 |
+
# parent_with_missing_item
|
71 |
+
({"x": "???", "a": 1, "b": {"c": 1}}, "b", "c", "b.c"),
|
72 |
+
({"foo": IntegerNode(value=10)}, "", "foo", "foo"),
|
73 |
+
({"foo": {"bar": IntegerNode(value=10)}}, "foo", "bar", "foo.bar"),
|
74 |
+
# enum
|
75 |
+
pytest.param(
|
76 |
+
DictConfig(key_type=Color, element_type=str, content={Color.RED: "red"}),
|
77 |
+
"RED",
|
78 |
+
"",
|
79 |
+
"RED",
|
80 |
+
id="get_full_key_with_enum_key",
|
81 |
+
),
|
82 |
+
pytest.param(
|
83 |
+
{
|
84 |
+
"foo": DictConfig(
|
85 |
+
key_type=Color, element_type=str, content={Color.RED: "red"}
|
86 |
+
)
|
87 |
+
},
|
88 |
+
"foo",
|
89 |
+
"RED",
|
90 |
+
"foo.RED",
|
91 |
+
id="get_full_key_with_nested_enum_key",
|
92 |
+
),
|
93 |
+
# slice
|
94 |
+
([1, 2, 3], "", slice(0, 1), "[0:1]"),
|
95 |
+
([1, 2, 3], "", slice(0, 1, 2), "[0:1:2]"),
|
96 |
+
],
|
97 |
+
)
|
98 |
+
def test_get_full_key_from_config(
|
99 |
+
cfg: Any, select: str, key: Any, expected: Any
|
100 |
+
) -> None:
|
101 |
+
c = OmegaConf.create(cfg)
|
102 |
+
_root, _last_key, node = c._select_impl(
|
103 |
+
select, throw_on_missing=True, throw_on_resolution_failure=True
|
104 |
+
)
|
105 |
+
assert node is not None
|
106 |
+
assert node._get_full_key(key) == expected
|
107 |
+
|
108 |
+
|
109 |
+
def test_value_node_get_full_key() -> None:
|
110 |
+
cfg = OmegaConf.create({"foo": IntegerNode(value=10)})
|
111 |
+
assert cfg._get_node("foo")._get_full_key(None) == "foo" # type: ignore
|
112 |
+
|
113 |
+
node = IntegerNode(value=10)
|
114 |
+
assert node._get_full_key(None) == ""
|
115 |
+
node = IntegerNode(key="foo", value=10)
|
116 |
+
assert node._get_full_key(None) == "foo"
|
tests/test_interpolation.py
ADDED
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
import re
|
4 |
+
from typing import Any, Dict
|
5 |
+
|
6 |
+
import pytest
|
7 |
+
|
8 |
+
from omegaconf import (
|
9 |
+
DictConfig,
|
10 |
+
IntegerNode,
|
11 |
+
ListConfig,
|
12 |
+
OmegaConf,
|
13 |
+
Resolver,
|
14 |
+
ValidationError,
|
15 |
+
)
|
16 |
+
|
17 |
+
|
18 |
+
def test_str_interpolation_dict_1() -> None:
|
19 |
+
# Simplest str_interpolation
|
20 |
+
c = OmegaConf.create(dict(a="${referenced}", referenced="bar"))
|
21 |
+
assert c.referenced == "bar"
|
22 |
+
assert c.a == "bar"
|
23 |
+
|
24 |
+
|
25 |
+
def test_str_interpolation_key_error_1() -> None:
|
26 |
+
# Test that a KeyError is thrown if an str_interpolation key is not available
|
27 |
+
c = OmegaConf.create(dict(a="${not_found}"))
|
28 |
+
|
29 |
+
with pytest.raises(KeyError):
|
30 |
+
_ = c.a
|
31 |
+
|
32 |
+
|
33 |
+
def test_str_interpolation_key_error_2() -> None:
|
34 |
+
# Test that a KeyError is thrown if an str_interpolation key is not available
|
35 |
+
c = OmegaConf.create(dict(a="${not.found}"))
|
36 |
+
|
37 |
+
with pytest.raises(KeyError):
|
38 |
+
c.a
|
39 |
+
|
40 |
+
|
41 |
+
def test_str_interpolation_3() -> None:
|
42 |
+
# Test that str_interpolation works with complex strings
|
43 |
+
c = OmegaConf.create(dict(a="the year ${year}", year="of the cat"))
|
44 |
+
|
45 |
+
assert c.a == "the year of the cat"
|
46 |
+
|
47 |
+
|
48 |
+
def test_str_interpolation_4() -> None:
|
49 |
+
# Test that a string with multiple str_interpolations works
|
50 |
+
c = OmegaConf.create(
|
51 |
+
dict(a="${ha} ${ha} ${ha}, said Pennywise, ${ha} ${ha}... ${ha}!", ha="HA")
|
52 |
+
)
|
53 |
+
|
54 |
+
assert c.a == "HA HA HA, said Pennywise, HA HA... HA!"
|
55 |
+
|
56 |
+
|
57 |
+
def test_deep_str_interpolation_1() -> None:
|
58 |
+
# Test deep str_interpolation works
|
59 |
+
c = OmegaConf.create(
|
60 |
+
dict(
|
61 |
+
a="the answer to the universe and everything is ${nested.value}",
|
62 |
+
nested=dict(value=42),
|
63 |
+
)
|
64 |
+
)
|
65 |
+
|
66 |
+
assert c.a == "the answer to the universe and everything is 42"
|
67 |
+
|
68 |
+
|
69 |
+
def test_deep_str_interpolation_2() -> None:
|
70 |
+
# Test that str_interpolation of a key that is nested works
|
71 |
+
c = OmegaConf.create(
|
72 |
+
dict(
|
73 |
+
out=42,
|
74 |
+
deep=dict(inside="the answer to the universe and everything is ${out}"),
|
75 |
+
)
|
76 |
+
)
|
77 |
+
|
78 |
+
assert c.deep.inside == "the answer to the universe and everything is 42"
|
79 |
+
|
80 |
+
|
81 |
+
def test_simple_str_interpolation_inherit_type() -> None:
|
82 |
+
# Test that str_interpolation of a key that is nested works
|
83 |
+
c = OmegaConf.create(
|
84 |
+
dict(
|
85 |
+
inter1="${answer1}",
|
86 |
+
inter2="${answer2}",
|
87 |
+
inter3="${answer3}",
|
88 |
+
inter4="${answer4}",
|
89 |
+
answer1=42,
|
90 |
+
answer2=42.0,
|
91 |
+
answer3=False,
|
92 |
+
answer4="string",
|
93 |
+
)
|
94 |
+
)
|
95 |
+
|
96 |
+
assert type(c.inter1) == int
|
97 |
+
assert type(c.inter2) == float
|
98 |
+
assert type(c.inter3) == bool
|
99 |
+
assert type(c.inter4) == str
|
100 |
+
|
101 |
+
|
102 |
+
def test_complex_str_interpolation_is_always_str_1() -> None:
|
103 |
+
c = OmegaConf.create(dict(two=2, four=4, inter1="${four}${two}", inter2="4${two}"))
|
104 |
+
|
105 |
+
assert type(c.inter1) == str
|
106 |
+
assert c.inter1 == "42"
|
107 |
+
assert type(c.inter2) == str
|
108 |
+
assert c.inter2 == "42"
|
109 |
+
|
110 |
+
|
111 |
+
@pytest.mark.parametrize( # type: ignore
|
112 |
+
"input_,key,expected",
|
113 |
+
[
|
114 |
+
(dict(a=10, b="${a}"), "b", 10),
|
115 |
+
(dict(a=10, b=[1, "${a}", 3, 4]), "b.1", 10),
|
116 |
+
(dict(a="${b.1}", b=[1, dict(c=10), 3, 4]), "a", dict(c=10)),
|
117 |
+
(dict(a="${b}", b=[1, 2]), "a", [1, 2]),
|
118 |
+
(dict(a="foo-${b}", b=[1, 2]), "a", "foo-[1, 2]"),
|
119 |
+
(dict(a="foo-${b}", b=dict(c=10)), "a", "foo-{'c': 10}"),
|
120 |
+
],
|
121 |
+
)
|
122 |
+
def test_interpolation(input_: Dict[str, Any], key: str, expected: str) -> None:
|
123 |
+
c = OmegaConf.create(input_)
|
124 |
+
assert OmegaConf.select(c, key) == expected
|
125 |
+
|
126 |
+
|
127 |
+
def test_2_step_interpolation() -> None:
|
128 |
+
c = OmegaConf.create(dict(src="bar", copy_src="${src}", copy_copy="${copy_src}"))
|
129 |
+
assert c.copy_src == "bar"
|
130 |
+
assert c.copy_copy == "bar"
|
131 |
+
|
132 |
+
|
133 |
+
def test_env_interpolation1() -> None:
|
134 |
+
try:
|
135 |
+
os.environ["foobar"] = "1234"
|
136 |
+
c = OmegaConf.create({"path": "/test/${env:foobar}"})
|
137 |
+
assert c.path == "/test/1234"
|
138 |
+
finally:
|
139 |
+
del os.environ["foobar"]
|
140 |
+
|
141 |
+
|
142 |
+
def test_env_interpolation_not_found() -> None:
|
143 |
+
c = OmegaConf.create({"path": "/test/${env:foobar}"})
|
144 |
+
with pytest.raises(
|
145 |
+
ValidationError, match=re.escape("Environment variable 'foobar' not found")
|
146 |
+
):
|
147 |
+
c.path
|
148 |
+
|
149 |
+
|
150 |
+
def test_env_default_str_interpolation_missing_env() -> None:
|
151 |
+
if os.getenv("foobar") is not None:
|
152 |
+
del os.environ["foobar"]
|
153 |
+
c = OmegaConf.create({"path": "/test/${env:foobar,abc}"})
|
154 |
+
assert c.path == "/test/abc"
|
155 |
+
|
156 |
+
|
157 |
+
def test_env_default_interpolation_missing_env_default_with_slash() -> None:
|
158 |
+
if os.getenv("foobar") is not None:
|
159 |
+
del os.environ["foobar"]
|
160 |
+
c = OmegaConf.create({"path": "${env:DATA_PATH,a/b}"})
|
161 |
+
assert c.path == "a/b"
|
162 |
+
|
163 |
+
|
164 |
+
def test_env_default_interpolation_env_exist() -> None:
|
165 |
+
os.environ["foobar"] = "1234"
|
166 |
+
c = OmegaConf.create({"path": "/test/${env:foobar,abc}"})
|
167 |
+
assert c.path == "/test/1234"
|
168 |
+
|
169 |
+
|
170 |
+
@pytest.mark.parametrize( # type: ignore
|
171 |
+
"value,expected",
|
172 |
+
[
|
173 |
+
# bool
|
174 |
+
("false", False),
|
175 |
+
("true", True),
|
176 |
+
# int
|
177 |
+
("10", 10),
|
178 |
+
("-10", -10),
|
179 |
+
# float
|
180 |
+
("10.0", 10.0),
|
181 |
+
("-10.0", -10.0),
|
182 |
+
# strings
|
183 |
+
("off", "off"),
|
184 |
+
("no", "no"),
|
185 |
+
("on", "on"),
|
186 |
+
("yes", "yes"),
|
187 |
+
(">1234", ">1234"),
|
188 |
+
(":1234", ":1234"),
|
189 |
+
("/1234", "/1234"),
|
190 |
+
# yaml strings are not getting parsed by the env resolver
|
191 |
+
("foo: bar", "foo: bar"),
|
192 |
+
("foo: \n - bar\n - baz", "foo: \n - bar\n - baz"),
|
193 |
+
],
|
194 |
+
)
|
195 |
+
def test_env_values_are_typed(value: Any, expected: Any) -> None:
|
196 |
+
try:
|
197 |
+
os.environ["my_key"] = value
|
198 |
+
c = OmegaConf.create(dict(my_key="${env:my_key}"))
|
199 |
+
assert c.my_key == expected
|
200 |
+
finally:
|
201 |
+
del os.environ["my_key"]
|
202 |
+
|
203 |
+
|
204 |
+
def test_register_resolver_twice_error(restore_resolvers: Any) -> None:
|
205 |
+
def foo() -> int:
|
206 |
+
return 10
|
207 |
+
|
208 |
+
OmegaConf.register_resolver("foo", foo)
|
209 |
+
with pytest.raises(AssertionError):
|
210 |
+
OmegaConf.register_resolver("foo", lambda: 10)
|
211 |
+
|
212 |
+
|
213 |
+
def test_clear_resolvers(restore_resolvers: Any) -> None:
|
214 |
+
assert OmegaConf.get_resolver("foo") is None
|
215 |
+
OmegaConf.register_resolver("foo", lambda x: int(x) + 10)
|
216 |
+
assert OmegaConf.get_resolver("foo") is not None
|
217 |
+
OmegaConf.clear_resolvers()
|
218 |
+
assert OmegaConf.get_resolver("foo") is None
|
219 |
+
|
220 |
+
|
221 |
+
def test_register_resolver_1(restore_resolvers: Any) -> None:
|
222 |
+
OmegaConf.register_resolver("plus_10", lambda x: int(x) + 10)
|
223 |
+
c = OmegaConf.create(dict(k="${plus_10:990}"))
|
224 |
+
|
225 |
+
assert type(c.k) == int
|
226 |
+
assert c.k == 1000
|
227 |
+
|
228 |
+
|
229 |
+
def test_resolver_cache_1(restore_resolvers: Any) -> None:
|
230 |
+
# resolvers are always converted to stateless idempotent functions
|
231 |
+
# subsequent calls to the same function with the same argument will always return the same value.
|
232 |
+
# this is important to allow embedding of functions like time() without having the value change during
|
233 |
+
# the program execution.
|
234 |
+
OmegaConf.register_resolver("random", lambda _: random.randint(0, 10000000))
|
235 |
+
c = OmegaConf.create(dict(k="${random:_}"))
|
236 |
+
assert c.k == c.k
|
237 |
+
|
238 |
+
|
239 |
+
def test_resolver_cache_2(restore_resolvers: Any) -> None:
|
240 |
+
"""
|
241 |
+
Tests that resolver cache is not shared between different OmegaConf objects
|
242 |
+
"""
|
243 |
+
OmegaConf.register_resolver("random", lambda _: random.randint(0, 10000000))
|
244 |
+
c1 = OmegaConf.create(dict(k="${random:_}"))
|
245 |
+
c2 = OmegaConf.create(dict(k="${random:_}"))
|
246 |
+
assert c1.k != c2.k
|
247 |
+
assert c1.k == c1.k
|
248 |
+
assert c2.k == c2.k
|
249 |
+
|
250 |
+
|
251 |
+
@pytest.mark.parametrize( # type: ignore
|
252 |
+
"resolver,name,key,result",
|
253 |
+
[
|
254 |
+
(lambda *args: args, "arg_list", "${my_resolver:cat, dog}", ("cat", "dog")),
|
255 |
+
(
|
256 |
+
lambda *args: args,
|
257 |
+
"escape_comma",
|
258 |
+
"${my_resolver:cat\\, do g}",
|
259 |
+
("cat, do g",),
|
260 |
+
),
|
261 |
+
(
|
262 |
+
lambda *args: args,
|
263 |
+
"escape_whitespace",
|
264 |
+
"${my_resolver:cat\\, do g}",
|
265 |
+
("cat, do g",),
|
266 |
+
),
|
267 |
+
(lambda: "zero", "zero_arg", "${my_resolver:}", "zero"),
|
268 |
+
],
|
269 |
+
)
|
270 |
+
def test_resolver_that_allows_a_list_of_arguments(
|
271 |
+
restore_resolvers: Any, resolver: Resolver, name: str, key: str, result: Any
|
272 |
+
) -> None:
|
273 |
+
OmegaConf.register_resolver("my_resolver", resolver)
|
274 |
+
c = OmegaConf.create({name: key})
|
275 |
+
assert isinstance(c, DictConfig)
|
276 |
+
assert c[name] == result
|
277 |
+
|
278 |
+
|
279 |
+
def test_copy_cache(restore_resolvers: Any) -> None:
|
280 |
+
OmegaConf.register_resolver("random", lambda _: random.randint(0, 10000000))
|
281 |
+
d = {"k": "${random:_}"}
|
282 |
+
c1 = OmegaConf.create(d)
|
283 |
+
assert c1.k == c1.k
|
284 |
+
|
285 |
+
c2 = OmegaConf.create(d)
|
286 |
+
assert c2.k != c1.k
|
287 |
+
OmegaConf.set_cache(c2, OmegaConf.get_cache(c1))
|
288 |
+
assert c2.k == c1.k
|
289 |
+
|
290 |
+
c3 = OmegaConf.create(d)
|
291 |
+
|
292 |
+
assert c3.k != c1.k
|
293 |
+
OmegaConf.copy_cache(c1, c3)
|
294 |
+
assert c3.k == c1.k
|
295 |
+
|
296 |
+
|
297 |
+
def test_clear_cache(restore_resolvers: Any) -> None:
|
298 |
+
OmegaConf.register_resolver("random", lambda _: random.randint(0, 10000000))
|
299 |
+
c = OmegaConf.create(dict(k="${random:_}"))
|
300 |
+
old = c.k
|
301 |
+
OmegaConf.clear_cache(c)
|
302 |
+
assert old != c.k
|
303 |
+
|
304 |
+
|
305 |
+
def test_supported_chars() -> None:
|
306 |
+
supported_chars = "%_-abc123."
|
307 |
+
c = OmegaConf.create(dict(dir1="${copy:" + supported_chars + "}"))
|
308 |
+
|
309 |
+
OmegaConf.register_resolver("copy", lambda x: x)
|
310 |
+
assert c.dir1 == supported_chars
|
311 |
+
|
312 |
+
|
313 |
+
def test_interpolation_in_list_key_error() -> None:
|
314 |
+
# Test that a KeyError is thrown if an str_interpolation key is not available
|
315 |
+
c = OmegaConf.create(["${10}"])
|
316 |
+
assert isinstance(c, ListConfig)
|
317 |
+
|
318 |
+
with pytest.raises(KeyError):
|
319 |
+
c[0]
|
320 |
+
|
321 |
+
|
322 |
+
def test_unsupported_interpolation_type() -> None:
|
323 |
+
c = OmegaConf.create(dict(foo="${wrong_type:ref}"))
|
324 |
+
|
325 |
+
with pytest.raises(ValueError):
|
326 |
+
c.foo
|
327 |
+
|
328 |
+
|
329 |
+
def test_incremental_dict_with_interpolation() -> None:
|
330 |
+
conf = OmegaConf.create()
|
331 |
+
assert isinstance(conf, DictConfig)
|
332 |
+
conf.a = 1
|
333 |
+
conf.b = OmegaConf.create()
|
334 |
+
assert isinstance(conf.b, DictConfig)
|
335 |
+
conf.b.c = "${a}"
|
336 |
+
assert conf.b.c == conf.a # type: ignore
|
337 |
+
|
338 |
+
|
339 |
+
@pytest.mark.parametrize( # type: ignore
|
340 |
+
"cfg,key,expected",
|
341 |
+
[
|
342 |
+
({"a": 10, "b": "${a}"}, "b", 10),
|
343 |
+
({"a": 10, "b": "${a}", "c": "${b}"}, "c", 10),
|
344 |
+
({"bar": 10, "foo": ["${bar}"]}, "foo.0", 10),
|
345 |
+
({"foo": None, "bar": "${foo}"}, "bar", None),
|
346 |
+
({"list": ["bar"], "foo": "${list.0}"}, "foo", "bar"),
|
347 |
+
({"list": ["${ref}"], "ref": "bar"}, "list.0", "bar"),
|
348 |
+
],
|
349 |
+
)
|
350 |
+
def test_interpolations(cfg: DictConfig, key: str, expected: Any) -> None:
|
351 |
+
c = OmegaConf.create(cfg)
|
352 |
+
assert OmegaConf.select(c, key) == expected
|
353 |
+
|
354 |
+
|
355 |
+
def test_interpolation_with_missing() -> None:
|
356 |
+
cfg = OmegaConf.create({"out_file": "${x.name}.txt", "x": {"name": "???"}})
|
357 |
+
assert OmegaConf.is_missing(cfg, "out_file")
|
358 |
+
|
359 |
+
|
360 |
+
def test_assign_to_interpolation() -> None:
|
361 |
+
cfg = OmegaConf.create(
|
362 |
+
{"foo": 10, "bar": "${foo}", "typed_bar": IntegerNode("${foo}")}
|
363 |
+
)
|
364 |
+
assert OmegaConf.is_interpolation(cfg, "bar")
|
365 |
+
assert cfg.bar == 10
|
366 |
+
assert cfg.typed_bar == 10
|
367 |
+
|
368 |
+
# assign regular field
|
369 |
+
cfg.bar = 20
|
370 |
+
assert not OmegaConf.is_interpolation(cfg, "bar")
|
371 |
+
|
372 |
+
with pytest.raises(ValidationError):
|
373 |
+
cfg.typed_bar = "nope"
|
374 |
+
cfg.typed_bar = 30
|
375 |
+
|
376 |
+
assert cfg.foo == 10
|
377 |
+
assert cfg.bar == 20
|
378 |
+
assert cfg.typed_bar == 30
|
379 |
+
|
380 |
+
|
381 |
+
def test_merge_with_interpolation() -> None:
|
382 |
+
cfg = OmegaConf.create(
|
383 |
+
{"foo": 10, "bar": "${foo}", "typed_bar": IntegerNode("${foo}")}
|
384 |
+
)
|
385 |
+
|
386 |
+
assert OmegaConf.merge(cfg, {"bar": 20}) == {"foo": 10, "bar": 20, "typed_bar": 10}
|
387 |
+
assert OmegaConf.merge(cfg, {"typed_bar": 30}) == {
|
388 |
+
"foo": 10,
|
389 |
+
"bar": 10,
|
390 |
+
"typed_bar": 30,
|
391 |
+
}
|
392 |
+
|
393 |
+
with pytest.raises(ValidationError):
|
394 |
+
OmegaConf.merge(cfg, {"typed_bar": "nope"})
|
395 |
+
|
396 |
+
|
397 |
+
def test_non_container_interpolation() -> None:
|
398 |
+
cfg = OmegaConf.create(dict(foo=0, bar="${foo.baz}"))
|
399 |
+
with pytest.raises(AssertionError):
|
400 |
+
cfg.bar
|
401 |
+
|
402 |
+
|
403 |
+
def test_indirect_interpolation() -> None:
|
404 |
+
d = {
|
405 |
+
"a": {"aa": 10},
|
406 |
+
"b": "${a}",
|
407 |
+
"c": "${b.aa}",
|
408 |
+
}
|
409 |
+
|
410 |
+
cfg = OmegaConf.create(d)
|
411 |
+
assert cfg.c == 10
|
412 |
+
assert OmegaConf.to_container(cfg, resolve=True) == {
|
413 |
+
"a": {"aa": 10},
|
414 |
+
"b": {"aa": 10},
|
415 |
+
"c": 10,
|
416 |
+
}
|
417 |
+
|
418 |
+
|
419 |
+
def test_indirect_interpolation2() -> None:
|
420 |
+
d = {
|
421 |
+
"a": {"aa": 10},
|
422 |
+
"b": "${a.aa}",
|
423 |
+
"c": "${b}",
|
424 |
+
}
|
425 |
+
|
426 |
+
cfg = OmegaConf.create(d)
|
427 |
+
assert cfg.c == 10
|
428 |
+
|
429 |
+
assert OmegaConf.to_container(cfg, resolve=True) == {
|
430 |
+
"a": {"aa": 10},
|
431 |
+
"b": 10,
|
432 |
+
"c": 10,
|
433 |
+
}
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import re
|
3 |
+
from typing import Any
|
4 |
+
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from omegaconf import (
|
8 |
+
BooleanNode,
|
9 |
+
DictConfig,
|
10 |
+
EnumNode,
|
11 |
+
FloatNode,
|
12 |
+
IntegerNode,
|
13 |
+
ListConfig,
|
14 |
+
OmegaConf,
|
15 |
+
StringNode,
|
16 |
+
ValidationError,
|
17 |
+
ValueNode,
|
18 |
+
)
|
19 |
+
|
20 |
+
from . import Color, Group
|
21 |
+
|
22 |
+
SKIP = object()
|
23 |
+
|
24 |
+
|
25 |
+
def verify(
|
26 |
+
cfg: Any,
|
27 |
+
key: Any,
|
28 |
+
none: bool,
|
29 |
+
opt: bool,
|
30 |
+
missing: bool,
|
31 |
+
inter: bool,
|
32 |
+
exp: Any = SKIP,
|
33 |
+
) -> None:
|
34 |
+
target_node = cfg._get_node(key)
|
35 |
+
assert target_node._key() == key
|
36 |
+
assert target_node._is_none() == none
|
37 |
+
assert target_node._is_optional() == opt
|
38 |
+
assert target_node._is_missing() == missing
|
39 |
+
assert target_node._is_interpolation() == inter
|
40 |
+
|
41 |
+
if exp is not SKIP:
|
42 |
+
assert cfg.get(key) == exp
|
43 |
+
|
44 |
+
assert OmegaConf.is_missing(cfg, key) == missing
|
45 |
+
assert OmegaConf.is_none(cfg, key) == none
|
46 |
+
assert OmegaConf.is_optional(cfg, key) == opt
|
47 |
+
assert OmegaConf.is_interpolation(cfg, key) == inter
|
48 |
+
|
49 |
+
|
50 |
+
# for each type Node type : int, bool, str, float, Color (enum) and User (@dataclass), DictConfig, ListConfig
|
51 |
+
# for each MISSING, None, Optional and interpolation:
|
52 |
+
@pytest.mark.parametrize(
|
53 |
+
"node_type, values",
|
54 |
+
[
|
55 |
+
(BooleanNode, [True, False]),
|
56 |
+
(FloatNode, [3.1415]),
|
57 |
+
(IntegerNode, [42]),
|
58 |
+
(StringNode, ["hello"]),
|
59 |
+
# EnumNode
|
60 |
+
(
|
61 |
+
lambda value, is_optional, key=None: EnumNode(
|
62 |
+
enum_type=Color, value=value, is_optional=is_optional, key=key
|
63 |
+
),
|
64 |
+
[Color.RED],
|
65 |
+
),
|
66 |
+
# DictConfig
|
67 |
+
(
|
68 |
+
lambda value, is_optional, key=None: DictConfig(
|
69 |
+
is_optional=is_optional, content=value, key=key
|
70 |
+
),
|
71 |
+
[{}, {"foo": "bar"}],
|
72 |
+
),
|
73 |
+
# ListConfig
|
74 |
+
(
|
75 |
+
lambda value, is_optional, key=None: ListConfig(
|
76 |
+
is_optional=is_optional, content=value, key=key
|
77 |
+
),
|
78 |
+
[[], [1, 2, 3]],
|
79 |
+
),
|
80 |
+
# dataclass
|
81 |
+
(
|
82 |
+
lambda value, is_optional, key=None: DictConfig(
|
83 |
+
ref_type=Group, is_optional=is_optional, content=value, key=key
|
84 |
+
),
|
85 |
+
[Group, Group()],
|
86 |
+
),
|
87 |
+
],
|
88 |
+
ids=(
|
89 |
+
"BooleanNode",
|
90 |
+
"FloatNode",
|
91 |
+
"IntegerNode",
|
92 |
+
"StringNode",
|
93 |
+
"EnumNode",
|
94 |
+
"DictConfig",
|
95 |
+
"ListConfig",
|
96 |
+
"dataclass",
|
97 |
+
),
|
98 |
+
)
|
99 |
+
class TestNodeTypesMatrix:
|
100 |
+
def test_none_assignment_and_merging_in_dict(
|
101 |
+
self, node_type: Any, values: Any
|
102 |
+
) -> None:
|
103 |
+
values = copy.deepcopy(values)
|
104 |
+
for value in values:
|
105 |
+
node = node_type(value=value, is_optional=False)
|
106 |
+
data = {"node": node}
|
107 |
+
cfg = OmegaConf.create(obj=data)
|
108 |
+
verify(cfg, "node", none=False, opt=False, missing=False, inter=False)
|
109 |
+
msg = "child 'node' is not Optional"
|
110 |
+
with pytest.raises(ValidationError, match=re.escape(msg)):
|
111 |
+
cfg.node = None
|
112 |
+
|
113 |
+
with pytest.raises(ValidationError):
|
114 |
+
OmegaConf.merge(cfg, {"node": None})
|
115 |
+
|
116 |
+
def test_dict_non_none_assignment(self, node_type: Any, values: Any) -> None:
|
117 |
+
values = copy.deepcopy(values)
|
118 |
+
for value in values:
|
119 |
+
value_backup = copy.deepcopy(value)
|
120 |
+
cfg = OmegaConf.create({"node": node_type(value=None, is_optional=True)})
|
121 |
+
verify(cfg, "node", none=True, opt=True, missing=False, inter=False)
|
122 |
+
|
123 |
+
cfg.node = value
|
124 |
+
assert cfg._get_node("node") == value
|
125 |
+
verify(cfg, "node", none=False, opt=True, missing=False, inter=False)
|
126 |
+
|
127 |
+
cfg.node = "???"
|
128 |
+
verify(cfg, "node", none=False, opt=True, missing=True, inter=False)
|
129 |
+
|
130 |
+
cfg.node = value_backup
|
131 |
+
assert cfg._get_node("node") == value_backup
|
132 |
+
verify(cfg, "node", none=False, opt=True, missing=False, inter=False)
|
133 |
+
|
134 |
+
def test_none_assignment_in_list(self, node_type: Any, values: Any) -> None:
|
135 |
+
values = copy.deepcopy(values)
|
136 |
+
for value in values:
|
137 |
+
key = 0
|
138 |
+
d = node_type(value=value, key=key, is_optional=False)
|
139 |
+
cfg = OmegaConf.create([d])
|
140 |
+
verify(cfg, key, none=False, opt=False, missing=False, inter=False)
|
141 |
+
|
142 |
+
with pytest.raises(ValidationError):
|
143 |
+
cfg[key] = None
|
144 |
+
|
145 |
+
def test_list_non_none_assignment(self, node_type: Any, values: Any) -> None:
|
146 |
+
values = copy.deepcopy(values)
|
147 |
+
for value in values:
|
148 |
+
key = 0
|
149 |
+
cfg = OmegaConf.create([node_type(value=None, key=key, is_optional=True)])
|
150 |
+
verify(cfg, key, none=True, opt=True, missing=False, inter=False)
|
151 |
+
|
152 |
+
cfg[key] = value
|
153 |
+
assert cfg[key] == value
|
154 |
+
verify(cfg, key, none=False, opt=True, missing=False, inter=False)
|
155 |
+
|
156 |
+
def test_none_construction(self, node_type: Any, values: Any) -> None:
|
157 |
+
values = copy.deepcopy(values)
|
158 |
+
node = node_type(value=None, is_optional=True)
|
159 |
+
if isinstance(node, ValueNode):
|
160 |
+
assert node._value() is None
|
161 |
+
assert node._is_optional()
|
162 |
+
assert node.__eq__(None)
|
163 |
+
assert OmegaConf.is_none(node)
|
164 |
+
|
165 |
+
for value in values:
|
166 |
+
node._set_value(value)
|
167 |
+
assert node.__eq__(value)
|
168 |
+
assert not node.__eq__(None)
|
169 |
+
assert not OmegaConf.is_none(node)
|
170 |
+
|
171 |
+
with pytest.raises(ValidationError):
|
172 |
+
node_type(value=None, is_optional=False)
|
173 |
+
|
174 |
+
def test_interpolation(
|
175 |
+
self, node_type: Any, values: Any, restore_resolvers: Any
|
176 |
+
) -> None:
|
177 |
+
resolver_output = 9999
|
178 |
+
OmegaConf.register_resolver("func", lambda: resolver_output)
|
179 |
+
values = copy.deepcopy(values)
|
180 |
+
for value in values:
|
181 |
+
node = {
|
182 |
+
"reg": node_type(value=value, is_optional=False),
|
183 |
+
"opt": node_type(value=value, is_optional=True),
|
184 |
+
}
|
185 |
+
cfg = OmegaConf.create(
|
186 |
+
{
|
187 |
+
"const": 10,
|
188 |
+
"primitive_missing": "???",
|
189 |
+
"resolver": StringNode(value="${func:}", is_optional=False),
|
190 |
+
"opt_resolver": StringNode(value="${func:}", is_optional=True),
|
191 |
+
"node": DictConfig(content=node, is_optional=False),
|
192 |
+
"opt_node": DictConfig(content=node, is_optional=True),
|
193 |
+
"reg": node_type(value=value, is_optional=False),
|
194 |
+
"opt": node_type(value=value, is_optional=True),
|
195 |
+
"opt_none": node_type(value=None, is_optional=True),
|
196 |
+
"missing": node_type(value="???", is_optional=False),
|
197 |
+
"opt_missing": node_type(value="???", is_optional=True),
|
198 |
+
# Interpolations
|
199 |
+
"int_reg": "${reg}",
|
200 |
+
"int_opt": "${opt}",
|
201 |
+
"int_opt_none": "${opt_none}",
|
202 |
+
"int_missing": "${missing}",
|
203 |
+
"int_opt_missing": "${opt_missing}",
|
204 |
+
"str_int_const": StringNode(
|
205 |
+
value="foo_${const}", is_optional=False
|
206 |
+
),
|
207 |
+
"opt_str_int_const": StringNode(
|
208 |
+
value="foo_${const}", is_optional=True
|
209 |
+
),
|
210 |
+
"str_int_with_primitive_missing": StringNode(
|
211 |
+
value="foo_${primitive_missing}", is_optional=False
|
212 |
+
),
|
213 |
+
"opt_str_int_with_primitive_missing": StringNode(
|
214 |
+
value="foo_${primitive_missing}", is_optional=True
|
215 |
+
),
|
216 |
+
"int_node": "${node}",
|
217 |
+
"int_opt_node": "${opt_node}",
|
218 |
+
"int_resolver": "${resolver}",
|
219 |
+
"int_opt_resolver": "${opt_resolver}",
|
220 |
+
}
|
221 |
+
)
|
222 |
+
|
223 |
+
verify(
|
224 |
+
cfg, "const", none=False, opt=True, missing=False, inter=False, exp=10
|
225 |
+
)
|
226 |
+
|
227 |
+
verify(
|
228 |
+
cfg,
|
229 |
+
"resolver",
|
230 |
+
none=False,
|
231 |
+
# Note, resolvers are always optional because the underlying function may return None
|
232 |
+
opt=True,
|
233 |
+
missing=False,
|
234 |
+
inter=True,
|
235 |
+
exp=resolver_output,
|
236 |
+
)
|
237 |
+
|
238 |
+
verify(
|
239 |
+
cfg,
|
240 |
+
"opt_resolver",
|
241 |
+
none=False,
|
242 |
+
opt=True,
|
243 |
+
missing=False,
|
244 |
+
inter=True,
|
245 |
+
exp=resolver_output,
|
246 |
+
)
|
247 |
+
|
248 |
+
verify(
|
249 |
+
cfg,
|
250 |
+
"reg",
|
251 |
+
none=False,
|
252 |
+
opt=False,
|
253 |
+
missing=False,
|
254 |
+
inter=False,
|
255 |
+
exp=value,
|
256 |
+
)
|
257 |
+
|
258 |
+
verify(
|
259 |
+
cfg, "opt", none=False, opt=True, missing=False, inter=False, exp=value
|
260 |
+
)
|
261 |
+
verify(
|
262 |
+
cfg,
|
263 |
+
"opt_none",
|
264 |
+
none=True,
|
265 |
+
opt=True,
|
266 |
+
missing=False,
|
267 |
+
inter=False,
|
268 |
+
exp=None,
|
269 |
+
)
|
270 |
+
verify(cfg, "missing", none=False, opt=False, missing=True, inter=False)
|
271 |
+
verify(cfg, "opt_missing", none=False, opt=True, missing=True, inter=False)
|
272 |
+
|
273 |
+
verify(
|
274 |
+
cfg,
|
275 |
+
"int_reg",
|
276 |
+
none=False,
|
277 |
+
opt=False,
|
278 |
+
missing=False,
|
279 |
+
inter=True,
|
280 |
+
exp=value,
|
281 |
+
)
|
282 |
+
verify(
|
283 |
+
cfg,
|
284 |
+
"int_opt",
|
285 |
+
none=False,
|
286 |
+
opt=True,
|
287 |
+
missing=False,
|
288 |
+
inter=True,
|
289 |
+
exp=value,
|
290 |
+
)
|
291 |
+
verify(
|
292 |
+
cfg,
|
293 |
+
"int_opt_none",
|
294 |
+
none=True,
|
295 |
+
opt=True,
|
296 |
+
missing=False,
|
297 |
+
inter=True,
|
298 |
+
exp=None,
|
299 |
+
)
|
300 |
+
verify(cfg, "int_missing", none=False, opt=False, missing=True, inter=True)
|
301 |
+
verify(
|
302 |
+
cfg, "int_opt_missing", none=False, opt=True, missing=True, inter=True
|
303 |
+
)
|
304 |
+
|
305 |
+
verify(
|
306 |
+
cfg,
|
307 |
+
"str_int_const",
|
308 |
+
none=False,
|
309 |
+
opt=False,
|
310 |
+
missing=False,
|
311 |
+
inter=True,
|
312 |
+
exp="foo_10",
|
313 |
+
)
|
314 |
+
verify(
|
315 |
+
cfg,
|
316 |
+
"opt_str_int_const",
|
317 |
+
none=False,
|
318 |
+
opt=True,
|
319 |
+
missing=False,
|
320 |
+
inter=True,
|
321 |
+
exp="foo_10",
|
322 |
+
)
|
323 |
+
verify(
|
324 |
+
cfg,
|
325 |
+
"int_node",
|
326 |
+
none=False,
|
327 |
+
opt=False,
|
328 |
+
missing=False,
|
329 |
+
inter=True,
|
330 |
+
exp=node,
|
331 |
+
)
|
332 |
+
|
333 |
+
verify(
|
334 |
+
cfg,
|
335 |
+
"int_opt_node",
|
336 |
+
none=False,
|
337 |
+
opt=True,
|
338 |
+
missing=False,
|
339 |
+
inter=True,
|
340 |
+
exp=node,
|
341 |
+
)
|
342 |
+
|
343 |
+
verify(
|
344 |
+
cfg,
|
345 |
+
"int_resolver",
|
346 |
+
none=False,
|
347 |
+
opt=True,
|
348 |
+
missing=False,
|
349 |
+
inter=True,
|
350 |
+
exp=resolver_output,
|
351 |
+
)
|
352 |
+
|
353 |
+
verify(
|
354 |
+
cfg,
|
355 |
+
"int_opt_resolver",
|
356 |
+
none=False,
|
357 |
+
opt=True,
|
358 |
+
missing=False,
|
359 |
+
inter=True,
|
360 |
+
exp=resolver_output,
|
361 |
+
)
|
362 |
+
|
363 |
+
verify(
|
364 |
+
cfg,
|
365 |
+
"str_int_with_primitive_missing",
|
366 |
+
none=False,
|
367 |
+
opt=False,
|
368 |
+
missing=True,
|
369 |
+
inter=True,
|
370 |
+
)
|
371 |
+
|
372 |
+
verify(
|
373 |
+
cfg,
|
374 |
+
"opt_str_int_with_primitive_missing",
|
375 |
+
none=False,
|
376 |
+
opt=True,
|
377 |
+
missing=True,
|
378 |
+
inter=True,
|
379 |
+
)
|
tests/test_merge.py
ADD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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from typing import Any, Dict, List, MutableMapping, MutableSequence, Tuple, Union
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from omegaconf import (
|
7 |
+
MISSING,
|
8 |
+
DictConfig,
|
9 |
+
ListConfig,
|
10 |
+
OmegaConf,
|
11 |
+
ReadonlyConfigError,
|
12 |
+
ValidationError,
|
13 |
+
nodes,
|
14 |
+
)
|
15 |
+
from omegaconf._utils import is_structured_config
|
16 |
+
from omegaconf.errors import ConfigKeyError
|
17 |
+
|
18 |
+
from . import (
|
19 |
+
A,
|
20 |
+
B,
|
21 |
+
C,
|
22 |
+
ConcretePlugin,
|
23 |
+
ConfWithMissingDict,
|
24 |
+
Group,
|
25 |
+
InterpolationDict,
|
26 |
+
InterpolationList,
|
27 |
+
MissingDict,
|
28 |
+
MissingList,
|
29 |
+
Package,
|
30 |
+
Plugin,
|
31 |
+
User,
|
32 |
+
Users,
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
@pytest.mark.parametrize( # type: ignore
|
37 |
+
"inputs, expected",
|
38 |
+
[
|
39 |
+
# dictionaries
|
40 |
+
([{}, {"a": 1}], {"a": 1}),
|
41 |
+
([{"a": None}, {"b": None}], {"a": None, "b": None}),
|
42 |
+
([{"a": 1}, {"b": 2}], {"a": 1, "b": 2}),
|
43 |
+
([{"a": {"a1": 1, "a2": 2}}, {"a": {"a1": 2}}], {"a": {"a1": 2, "a2": 2}}),
|
44 |
+
([{"a": 1, "b": 2}, {"b": 3}], {"a": 1, "b": 3}),
|
45 |
+
(({"a": 1, "b": 2}, {"b": {"c": 3}}), {"a": 1, "b": {"c": 3}}),
|
46 |
+
(({"b": {"c": 1}}, {"b": 1}), {"b": 1}),
|
47 |
+
(({"list": [1, 2, 3]}, {"list": [4, 5, 6]}), {"list": [4, 5, 6]}),
|
48 |
+
(({"a": 1}, {"a": nodes.IntegerNode(10)}), {"a": 10}),
|
49 |
+
(({"a": 1}, {"a": nodes.IntegerNode(10)}), {"a": nodes.IntegerNode(10)}),
|
50 |
+
(({"a": nodes.IntegerNode(10)}, {"a": 1}), {"a": 1}),
|
51 |
+
(({"a": nodes.IntegerNode(10)}, {"a": 1}), {"a": nodes.IntegerNode(1)}),
|
52 |
+
pytest.param(
|
53 |
+
({"a": "???"}, {"a": {}}), {"a": {}}, id="dict_merge_into_missing"
|
54 |
+
),
|
55 |
+
pytest.param(
|
56 |
+
({"a": "???"}, {"a": {"b": 10}}),
|
57 |
+
{"a": {"b": 10}},
|
58 |
+
id="dict_merge_into_missing",
|
59 |
+
),
|
60 |
+
pytest.param(
|
61 |
+
({"a": {"b": 10}}, {"a": "???"}),
|
62 |
+
{"a": "???"},
|
63 |
+
id="dict_merge_missing_onto",
|
64 |
+
),
|
65 |
+
# lists
|
66 |
+
(([1, 2, 3], [4, 5, 6]), [4, 5, 6]),
|
67 |
+
(([[1, 2, 3]], [[4, 5, 6]]), [[4, 5, 6]]),
|
68 |
+
(([1, 2, {"a": 10}], [4, 5, {"b": 20}]), [4, 5, {"b": 20}]),
|
69 |
+
pytest.param(
|
70 |
+
({"a": "???"}, {"a": []}), {"a": []}, id="list_merge_into_missing"
|
71 |
+
),
|
72 |
+
pytest.param(
|
73 |
+
({"a": "???"}, {"a": [1, 2, 3]}),
|
74 |
+
{"a": [1, 2, 3]},
|
75 |
+
id="list_merge_into_missing",
|
76 |
+
),
|
77 |
+
pytest.param(
|
78 |
+
({"a": [1, 2, 3]}, {"a": "???"}),
|
79 |
+
{"a": "???"},
|
80 |
+
id="list_merge_missing_onto",
|
81 |
+
),
|
82 |
+
pytest.param(
|
83 |
+
([1, 2, 3], ListConfig(content=MISSING)),
|
84 |
+
ListConfig(content=MISSING),
|
85 |
+
id="list_merge_missing_onto2",
|
86 |
+
),
|
87 |
+
# Interpolations
|
88 |
+
# value interpolation
|
89 |
+
pytest.param(
|
90 |
+
({"d1": 1, "inter": "${d1}"}, {"d1": 2}),
|
91 |
+
{"d1": 2, "inter": 2},
|
92 |
+
id="inter:updating_data",
|
93 |
+
),
|
94 |
+
pytest.param(
|
95 |
+
({"d1": 1, "d2": 2, "inter": "${d1}"}, {"inter": "${d2}"}),
|
96 |
+
{"d1": 1, "d2": 2, "inter": 2},
|
97 |
+
id="inter:value_inter_over_value_inter",
|
98 |
+
),
|
99 |
+
pytest.param(
|
100 |
+
({"inter": "${d1}"}, {"inter": 123}),
|
101 |
+
{"inter": 123},
|
102 |
+
id="inter:data_over_value_inter",
|
103 |
+
),
|
104 |
+
pytest.param(
|
105 |
+
({"inter": "${d1}", "d1": 1, "n1": {"foo": "bar"}}, {"inter": "${n1}"}),
|
106 |
+
{"inter": {"foo": "bar"}, "d1": 1, "n1": {"foo": "bar"}},
|
107 |
+
id="inter:node_inter_over_value_inter",
|
108 |
+
),
|
109 |
+
pytest.param(
|
110 |
+
({"inter": 123}, {"inter": "${data}"}),
|
111 |
+
{"inter": "${data}"},
|
112 |
+
id="inter:inter_over_data",
|
113 |
+
),
|
114 |
+
# node interpolation
|
115 |
+
pytest.param(
|
116 |
+
({"n": {"a": 10}, "i": "${n}"}, {"n": {"a": 20}}),
|
117 |
+
{"n": {"a": 20}, "i": {"a": 20}},
|
118 |
+
id="node_inter:node_update",
|
119 |
+
),
|
120 |
+
pytest.param(
|
121 |
+
({"d": 20, "n": {"a": 10}, "i": "${n}"}, {"i": "${d}"}),
|
122 |
+
{"d": 20, "n": {"a": 10}, "i": 20},
|
123 |
+
id="node_inter:value_inter_over_node_inter",
|
124 |
+
),
|
125 |
+
pytest.param(
|
126 |
+
({"n": {"a": 10}, "i": "${n}"}, {"i": 30}),
|
127 |
+
{"n": {"a": 10}, "i": 30},
|
128 |
+
id="node_inter:data_over_node_inter",
|
129 |
+
),
|
130 |
+
pytest.param(
|
131 |
+
({"n1": {"a": 10}, "n2": {"b": 20}, "i": "${n1}"}, {"i": "${n2}"}),
|
132 |
+
{"n1": {"a": 10}, "n2": {"b": 20}, "i": {"b": 20}},
|
133 |
+
id="node_inter:node_inter_over_node_inter",
|
134 |
+
),
|
135 |
+
pytest.param(
|
136 |
+
({"v": 10, "n": {"a": 20}}, {"v": "${n}"}),
|
137 |
+
{"v": {"a": 20}, "n": {"a": 20}},
|
138 |
+
id="inter:node_inter_over_data",
|
139 |
+
),
|
140 |
+
pytest.param(
|
141 |
+
({"n": {"a": 10}, "i": "${n}"}, {"i": {"b": 20}}),
|
142 |
+
{"n": {"a": 10}, "i": {"a": 10, "b": 20}},
|
143 |
+
id="inter:node_over_node_interpolation",
|
144 |
+
),
|
145 |
+
# Structured configs
|
146 |
+
(({"user": User}, {}), {"user": User(name=MISSING, age=MISSING)}),
|
147 |
+
(({"user": User}, {"user": {}}), {"user": User(name=MISSING, age=MISSING)}),
|
148 |
+
(
|
149 |
+
({"user": User}, {"user": {"name": "Joe"}}),
|
150 |
+
{"user": User(name="Joe", age=MISSING)},
|
151 |
+
),
|
152 |
+
(
|
153 |
+
({"user": User}, {"user": {"name": "Joe", "age": 10}}),
|
154 |
+
{"user": User(name="Joe", age=10)},
|
155 |
+
),
|
156 |
+
([{"users": Users}], {"users": {"name2user": {}}}),
|
157 |
+
([Users], {"name2user": {}}),
|
158 |
+
([Users, {"name2user": {}}], {"name2user": {}}),
|
159 |
+
(
|
160 |
+
[Users, {"name2user": {"joe": User}}],
|
161 |
+
{"name2user": {"joe": {"name": MISSING, "age": MISSING}}},
|
162 |
+
),
|
163 |
+
(
|
164 |
+
[Users, {"name2user": {"joe": User(name="joe")}}],
|
165 |
+
{"name2user": {"joe": {"name": "joe", "age": MISSING}}},
|
166 |
+
),
|
167 |
+
pytest.param(
|
168 |
+
[Users, {"name2user": {"joe": {"name": "joe"}}}],
|
169 |
+
{"name2user": {"joe": {"name": "joe", "age": MISSING}}},
|
170 |
+
id="users_merge_with_missing_age",
|
171 |
+
),
|
172 |
+
pytest.param(
|
173 |
+
[ConfWithMissingDict, {"dict": {"foo": "bar"}}],
|
174 |
+
{"dict": {"foo": "bar"}},
|
175 |
+
id="conf_missing_dict",
|
176 |
+
),
|
177 |
+
pytest.param(
|
178 |
+
[{}, ConfWithMissingDict],
|
179 |
+
{"dict": "???"},
|
180 |
+
id="merge_missing_dict_into_missing_dict",
|
181 |
+
),
|
182 |
+
([{"user": User}, {"user": Group}], pytest.raises(ValidationError)),
|
183 |
+
(
|
184 |
+
[{"user": DictConfig(ref_type=User, content=User)}, {"user": Group}],
|
185 |
+
pytest.raises(ValidationError),
|
186 |
+
),
|
187 |
+
([Plugin, ConcretePlugin], ConcretePlugin),
|
188 |
+
pytest.param(
|
189 |
+
[{"user": "???"}, {"user": Group}],
|
190 |
+
{"user": Group},
|
191 |
+
id="merge_into_missing_node",
|
192 |
+
),
|
193 |
+
([{"user": User()}, {"user": {"foo": "bar"}}], pytest.raises(ConfigKeyError)),
|
194 |
+
# missing DictConfig
|
195 |
+
pytest.param(
|
196 |
+
[{"dict": DictConfig(content="???")}, {"dict": {"foo": "bar"}}],
|
197 |
+
{"dict": {"foo": "bar"}},
|
198 |
+
id="merge_into_missing_DictConfig",
|
199 |
+
),
|
200 |
+
# missing Dict[str, str]
|
201 |
+
pytest.param(
|
202 |
+
[MissingDict, {"dict": {"foo": "bar"}}],
|
203 |
+
{"dict": {"foo": "bar"}},
|
204 |
+
id="merge_into_missing_Dict[str,str]",
|
205 |
+
),
|
206 |
+
# missing ListConfig
|
207 |
+
pytest.param(
|
208 |
+
[{"list": ListConfig(content="???")}, {"list": [1, 2, 3]}],
|
209 |
+
{"list": [1, 2, 3]},
|
210 |
+
id="merge_into_missing_ListConfig",
|
211 |
+
),
|
212 |
+
# missing List[str]
|
213 |
+
pytest.param(
|
214 |
+
[MissingList, {"list": ["a", "b", "c"]}],
|
215 |
+
{"list": ["a", "b", "c"]},
|
216 |
+
id="merge_into_missing_List[str]",
|
217 |
+
),
|
218 |
+
# merging compatible dict into MISSING structured config expands it
|
219 |
+
# to ensure the resulting node follows the protocol set by the underlying type
|
220 |
+
pytest.param(
|
221 |
+
[B, {"x": {}}], {"x": {"a": 10}}, id="structured_merge_into_missing"
|
222 |
+
),
|
223 |
+
pytest.param(
|
224 |
+
[B, {"x": {"a": 20}}], {"x": {"a": 20}}, id="structured_merge_into_missing"
|
225 |
+
),
|
226 |
+
pytest.param([C, {"x": A}], {"x": {"a": 10}}, id="structured_merge_into_none"),
|
227 |
+
pytest.param([C, C], {"x": None}, id="none_not_expanding"),
|
228 |
+
# Merge into list with Structured Config
|
229 |
+
pytest.param(
|
230 |
+
[ListConfig(content=[], element_type=User), [{}]],
|
231 |
+
[User()],
|
232 |
+
id="list_sc_element_merge_dict",
|
233 |
+
),
|
234 |
+
pytest.param(
|
235 |
+
[ListConfig(content=[], element_type=User), [{"name": "Bond", "age": 7}]],
|
236 |
+
[User(name="Bond", age=7)],
|
237 |
+
id="list_sc_element_merge_dict",
|
238 |
+
),
|
239 |
+
pytest.param(
|
240 |
+
[ListConfig(content=[], element_type=User), [{"name": "Bond"}]],
|
241 |
+
[User(name="Bond", age=MISSING)],
|
242 |
+
id="list_sc_element_merge_dict",
|
243 |
+
),
|
244 |
+
],
|
245 |
+
)
|
246 |
+
def test_merge(inputs: Any, expected: Any) -> None:
|
247 |
+
configs = [OmegaConf.create(c) for c in inputs]
|
248 |
+
|
249 |
+
if isinstance(expected, (MutableMapping, MutableSequence)) or is_structured_config(
|
250 |
+
expected
|
251 |
+
):
|
252 |
+
merged = OmegaConf.merge(*configs)
|
253 |
+
assert merged == expected
|
254 |
+
# test input configs are not changed.
|
255 |
+
# Note that converting to container without resolving to avoid resolution errors while comparing
|
256 |
+
for i in range(len(inputs)):
|
257 |
+
input_i = OmegaConf.create(inputs[i])
|
258 |
+
orig = OmegaConf.to_container(input_i, resolve=False)
|
259 |
+
merged2 = OmegaConf.to_container(configs[i], resolve=False)
|
260 |
+
assert orig == merged2
|
261 |
+
else:
|
262 |
+
with expected:
|
263 |
+
OmegaConf.merge(*configs)
|
264 |
+
|
265 |
+
|
266 |
+
def test_merge_error_retains_type() -> None:
|
267 |
+
cfg = OmegaConf.structured(ConcretePlugin)
|
268 |
+
with pytest.raises(ValidationError):
|
269 |
+
cfg.merge_with({"params": {"foo": "error"}})
|
270 |
+
assert OmegaConf.get_type(cfg) == ConcretePlugin
|
271 |
+
|
272 |
+
|
273 |
+
def test_primitive_dicts() -> None:
|
274 |
+
c1 = {"a": 10}
|
275 |
+
c2 = {"b": 20}
|
276 |
+
merged = OmegaConf.merge(c1, c2)
|
277 |
+
assert merged == {"a": 10, "b": 20}
|
278 |
+
|
279 |
+
|
280 |
+
@pytest.mark.parametrize( # type: ignore
|
281 |
+
"a_, b_, expected", [((1, 2, 3), (4, 5, 6), [4, 5, 6])]
|
282 |
+
)
|
283 |
+
def test_merge_no_eq_verify(
|
284 |
+
a_: Tuple[int], b_: Tuple[int], expected: Tuple[int]
|
285 |
+
) -> None:
|
286 |
+
a = OmegaConf.create(a_)
|
287 |
+
b = OmegaConf.create(b_)
|
288 |
+
c = OmegaConf.merge(a, b)
|
289 |
+
# verify merge result is expected
|
290 |
+
assert expected == c
|
291 |
+
|
292 |
+
|
293 |
+
@pytest.mark.parametrize( # type: ignore
|
294 |
+
"c1,c2,expected",
|
295 |
+
[({}, {"a": 1, "b": 2}, {"a": 1, "b": 2}), ({"a": 1}, {"b": 2}, {"a": 1, "b": 2})],
|
296 |
+
)
|
297 |
+
def test_merge_with(c1: Any, c2: Any, expected: Any) -> None:
|
298 |
+
a = OmegaConf.create(c1)
|
299 |
+
b = OmegaConf.create(c2)
|
300 |
+
a.merge_with(b)
|
301 |
+
assert a == expected
|
302 |
+
|
303 |
+
|
304 |
+
@pytest.mark.parametrize( # type: ignore
|
305 |
+
"c1,c2,expected",
|
306 |
+
[({}, {"a": 1, "b": 2}, {"a": 1, "b": 2}), ({"a": 1}, {"b": 2}, {"a": 1, "b": 2})],
|
307 |
+
)
|
308 |
+
def test_merge_with_c2_readonly(c1: Any, c2: Any, expected: Any) -> None:
|
309 |
+
a = OmegaConf.create(c1)
|
310 |
+
b = OmegaConf.create(c2)
|
311 |
+
OmegaConf.set_readonly(b, True)
|
312 |
+
a.merge_with(b)
|
313 |
+
assert a == expected
|
314 |
+
assert OmegaConf.is_readonly(a)
|
315 |
+
|
316 |
+
|
317 |
+
def test_3way_dict_merge() -> None:
|
318 |
+
c1 = OmegaConf.create("{a: 1, b: 2}")
|
319 |
+
c2 = OmegaConf.create("{b: 3}")
|
320 |
+
c3 = OmegaConf.create("{a: 2, c: 3}")
|
321 |
+
c4 = OmegaConf.merge(c1, c2, c3)
|
322 |
+
assert {"a": 2, "b": 3, "c": 3} == c4
|
323 |
+
|
324 |
+
|
325 |
+
def test_merge_list_list() -> None:
|
326 |
+
a = OmegaConf.create([1, 2, 3])
|
327 |
+
b = OmegaConf.create([4, 5, 6])
|
328 |
+
a.merge_with(b)
|
329 |
+
assert a == b
|
330 |
+
|
331 |
+
|
332 |
+
@pytest.mark.parametrize( # type: ignore
|
333 |
+
"base, merge, exception",
|
334 |
+
[
|
335 |
+
({}, [], TypeError),
|
336 |
+
([], {}, TypeError),
|
337 |
+
([1, 2, 3], None, ValueError),
|
338 |
+
({"a": 10}, None, ValueError),
|
339 |
+
(Package, {"modules": [{"foo": "var"}]}, ConfigKeyError),
|
340 |
+
],
|
341 |
+
)
|
342 |
+
def test_merge_error(base: Any, merge: Any, exception: Any) -> None:
|
343 |
+
base = OmegaConf.create(base)
|
344 |
+
merge = None if merge is None else OmegaConf.create(merge)
|
345 |
+
with pytest.raises(exception):
|
346 |
+
OmegaConf.merge(base, merge)
|
347 |
+
|
348 |
+
|
349 |
+
@pytest.mark.parametrize( # type: ignore
|
350 |
+
"c1, c2",
|
351 |
+
[
|
352 |
+
pytest.param({"foo": "bar"}, {"zoo": "foo"}, id="dict"),
|
353 |
+
pytest.param([1, 2, 3], [4, 5, 6], id="list"),
|
354 |
+
],
|
355 |
+
)
|
356 |
+
def test_with_readonly_c1(c1: Any, c2: Any) -> None:
|
357 |
+
cfg1 = OmegaConf.create(c1)
|
358 |
+
cfg2 = OmegaConf.create(c2)
|
359 |
+
OmegaConf.set_readonly(cfg1, True)
|
360 |
+
cfg3 = OmegaConf.merge(cfg1, cfg2)
|
361 |
+
assert OmegaConf.is_readonly(cfg3)
|
362 |
+
|
363 |
+
|
364 |
+
@pytest.mark.parametrize( # type: ignore
|
365 |
+
"c1, c2",
|
366 |
+
[
|
367 |
+
pytest.param({"foo": "bar"}, {"zoo": "foo"}, id="dict"),
|
368 |
+
pytest.param([1, 2, 3], [4, 5, 6], id="list"),
|
369 |
+
],
|
370 |
+
)
|
371 |
+
def test_with_readonly_c2(c1: Any, c2: Any) -> None:
|
372 |
+
cfg1 = OmegaConf.create(c1)
|
373 |
+
cfg2 = OmegaConf.create(c1)
|
374 |
+
OmegaConf.set_readonly(cfg2, True)
|
375 |
+
cfg3 = OmegaConf.merge(cfg1, cfg2)
|
376 |
+
assert OmegaConf.is_readonly(cfg3)
|
377 |
+
|
378 |
+
|
379 |
+
@pytest.mark.parametrize( # type: ignore
|
380 |
+
"c1, c2", [({"foo": "bar"}, {"zoo": "foo"}), ([1, 2, 3], [4, 5, 6])]
|
381 |
+
)
|
382 |
+
def test_into_readonly(c1: Any, c2: Any) -> None:
|
383 |
+
cfg = OmegaConf.create(c1)
|
384 |
+
OmegaConf.set_readonly(cfg, True)
|
385 |
+
with pytest.raises(ReadonlyConfigError):
|
386 |
+
cfg.merge_with(c2)
|
387 |
+
|
388 |
+
|
389 |
+
@pytest.mark.parametrize( # type: ignore
|
390 |
+
"c1, c2, expected",
|
391 |
+
[
|
392 |
+
(
|
393 |
+
{"node": {"foo": "bar"}},
|
394 |
+
{"node": {"zoo": "foo"}},
|
395 |
+
{"node": {"foo": "bar", "zoo": "foo"}},
|
396 |
+
),
|
397 |
+
],
|
398 |
+
)
|
399 |
+
def test_dict_merge_readonly_into_readwrite(c1: Any, c2: Any, expected: Any) -> None:
|
400 |
+
c1 = OmegaConf.create(c1)
|
401 |
+
c2 = OmegaConf.create(c2)
|
402 |
+
OmegaConf.set_readonly(c2.node, True)
|
403 |
+
with pytest.raises(ReadonlyConfigError):
|
404 |
+
c2.node.foo = 10
|
405 |
+
assert OmegaConf.merge(c1, c2) == expected
|
406 |
+
c1.merge_with(c2)
|
407 |
+
assert c1 == expected
|
408 |
+
|
409 |
+
|
410 |
+
@pytest.mark.parametrize( # type: ignore
|
411 |
+
"c1, c2, expected",
|
412 |
+
[({"node": [1, 2, 3]}, {"node": [4, 5, 6]}, {"node": [4, 5, 6]})],
|
413 |
+
)
|
414 |
+
def test_list_merge_readonly_into_readwrite(c1: Any, c2: Any, expected: Any) -> None:
|
415 |
+
c1 = OmegaConf.create(c1)
|
416 |
+
c2 = OmegaConf.create(c2)
|
417 |
+
OmegaConf.set_readonly(c2.node, True)
|
418 |
+
with pytest.raises(ReadonlyConfigError):
|
419 |
+
c2.node.append(10)
|
420 |
+
assert OmegaConf.merge(c1, c2) == expected
|
421 |
+
c1.merge_with(c2)
|
422 |
+
assert c1 == expected
|
423 |
+
|
424 |
+
|
425 |
+
def test_parent_maintained() -> None:
|
426 |
+
c1 = OmegaConf.create({"a": {"b": 10}})
|
427 |
+
c2 = OmegaConf.create({"aa": {"bb": 100}})
|
428 |
+
c3 = OmegaConf.merge(c1, c2)
|
429 |
+
assert isinstance(c1, DictConfig)
|
430 |
+
assert isinstance(c2, DictConfig)
|
431 |
+
assert isinstance(c3, DictConfig)
|
432 |
+
assert id(c1.a._get_parent()) == id(c1)
|
433 |
+
assert id(c2.aa._get_parent()) == id(c2)
|
434 |
+
assert id(c3.a._get_parent()) == id(c3)
|
435 |
+
|
436 |
+
|
437 |
+
@pytest.mark.parametrize( # type:ignore
|
438 |
+
"cfg,overrides,expected",
|
439 |
+
[
|
440 |
+
([1, 2, 3], ["0=bar", "2.a=100"], ["bar", 2, dict(a=100)]),
|
441 |
+
({}, ["foo=bar", "bar=100"], {"foo": "bar", "bar": 100}),
|
442 |
+
({}, ["foo=bar=10"], {"foo": "bar=10"}),
|
443 |
+
],
|
444 |
+
)
|
445 |
+
def test_merge_with_dotlist(
|
446 |
+
cfg: Union[List[Any], Dict[str, Any]],
|
447 |
+
overrides: List[str],
|
448 |
+
expected: Union[List[Any], Dict[str, Any]],
|
449 |
+
) -> None:
|
450 |
+
c = OmegaConf.create(cfg)
|
451 |
+
c.merge_with_dotlist(overrides)
|
452 |
+
assert c == expected
|
453 |
+
|
454 |
+
|
455 |
+
def test_merge_with_cli() -> None:
|
456 |
+
c = OmegaConf.create([1, 2, 3])
|
457 |
+
sys.argv = ["app.py", "0=bar", "2.a=100"]
|
458 |
+
c.merge_with_cli()
|
459 |
+
assert c == ["bar", 2, dict(a=100)]
|
460 |
+
|
461 |
+
|
462 |
+
@pytest.mark.parametrize( # type:ignore
|
463 |
+
"dotlist, expected",
|
464 |
+
[([], {}), (["foo=1"], {"foo": 1}), (["foo=1", "bar"], {"foo": 1, "bar": None})],
|
465 |
+
)
|
466 |
+
def test_merge_empty_with_dotlist(dotlist: List[str], expected: Dict[str, Any]) -> None:
|
467 |
+
c = OmegaConf.create()
|
468 |
+
c.merge_with_dotlist(dotlist)
|
469 |
+
assert c == expected
|
470 |
+
|
471 |
+
|
472 |
+
@pytest.mark.parametrize("dotlist", ["foo=10", ["foo=1", 10]]) # type:ignore
|
473 |
+
def test_merge_with_dotlist_errors(dotlist: List[str]) -> None:
|
474 |
+
c = OmegaConf.create()
|
475 |
+
with pytest.raises(ValueError):
|
476 |
+
c.merge_with_dotlist(dotlist)
|
477 |
+
|
478 |
+
|
479 |
+
@pytest.mark.parametrize( # type:ignore
|
480 |
+
"dst, other, expected, node",
|
481 |
+
[
|
482 |
+
pytest.param(
|
483 |
+
OmegaConf.structured(InterpolationList),
|
484 |
+
OmegaConf.create({"list": [0.1]}),
|
485 |
+
{"list": [0.1]},
|
486 |
+
"list",
|
487 |
+
id="merge_interpolation_list_with_list",
|
488 |
+
),
|
489 |
+
pytest.param(
|
490 |
+
OmegaConf.structured(InterpolationDict),
|
491 |
+
OmegaConf.create({"dict": {"a": 4}}),
|
492 |
+
{"dict": {"a": 4}},
|
493 |
+
"dict",
|
494 |
+
id="merge_interpolation_dict_with_dict",
|
495 |
+
),
|
496 |
+
],
|
497 |
+
)
|
498 |
+
def test_merge_with_src_as_interpolation(
|
499 |
+
dst: Any, other: Any, expected: Any, node: Any
|
500 |
+
) -> None:
|
501 |
+
res = OmegaConf.merge(dst, other)
|
502 |
+
assert res == expected
|
503 |
+
|
504 |
+
|
505 |
+
@pytest.mark.parametrize( # type:ignore
|
506 |
+
"dst, other, node",
|
507 |
+
[
|
508 |
+
pytest.param(
|
509 |
+
OmegaConf.structured(InterpolationDict),
|
510 |
+
OmegaConf.structured(InterpolationDict),
|
511 |
+
"dict",
|
512 |
+
id="merge_interpolation_dict_with_interpolation_dict",
|
513 |
+
),
|
514 |
+
pytest.param(
|
515 |
+
OmegaConf.structured(InterpolationList),
|
516 |
+
OmegaConf.structured(InterpolationList),
|
517 |
+
"list",
|
518 |
+
id="merge_interpolation_list_with_interpolation_list",
|
519 |
+
),
|
520 |
+
],
|
521 |
+
)
|
522 |
+
def test_merge_with_other_as_interpolation(dst: Any, other: Any, node: Any) -> None:
|
523 |
+
res = OmegaConf.merge(dst, other)
|
524 |
+
assert OmegaConf.is_interpolation(res, node)
|
tests/test_nodes.py
ADDED
@@ -0,0 +1,552 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
BooleanNode,
|
10 |
+
DictConfig,
|
11 |
+
EnumNode,
|
12 |
+
FloatNode,
|
13 |
+
IntegerNode,
|
14 |
+
ListConfig,
|
15 |
+
OmegaConf,
|
16 |
+
StringNode,
|
17 |
+
ValueNode,
|
18 |
+
)
|
19 |
+
from omegaconf.errors import ValidationError
|
20 |
+
|
21 |
+
from . import Color, IllegalType, User
|
22 |
+
|
23 |
+
|
24 |
+
# testing valid conversions
|
25 |
+
@pytest.mark.parametrize( # type: ignore
|
26 |
+
"type_,input_,output_",
|
27 |
+
[
|
28 |
+
# string
|
29 |
+
(StringNode, "abc", "abc"),
|
30 |
+
(StringNode, 100, "100"),
|
31 |
+
# integer
|
32 |
+
(IntegerNode, 10, 10),
|
33 |
+
(IntegerNode, "10", 10),
|
34 |
+
(IntegerNode, -100, -100),
|
35 |
+
(IntegerNode, "-100", -100),
|
36 |
+
# float
|
37 |
+
(FloatNode, float("inf"), float("inf")),
|
38 |
+
# Yes, we treat nan as equal to nan in OmegaConf
|
39 |
+
(FloatNode, float("nan"), float("nan")),
|
40 |
+
(FloatNode, 10, 10.0),
|
41 |
+
(FloatNode, 10.1, 10.1),
|
42 |
+
(FloatNode, "10.2", 10.2),
|
43 |
+
(FloatNode, "10e-3", 10e-3),
|
44 |
+
# bool true
|
45 |
+
(BooleanNode, True, True),
|
46 |
+
(BooleanNode, "Y", True),
|
47 |
+
(BooleanNode, "true", True),
|
48 |
+
(BooleanNode, "Yes", True),
|
49 |
+
(BooleanNode, "On", True),
|
50 |
+
(BooleanNode, "1", True),
|
51 |
+
(BooleanNode, 100, True),
|
52 |
+
# bool false
|
53 |
+
(BooleanNode, False, False),
|
54 |
+
(BooleanNode, "N", False),
|
55 |
+
(BooleanNode, "false", False),
|
56 |
+
(BooleanNode, "No", False),
|
57 |
+
(BooleanNode, "Off", False),
|
58 |
+
(BooleanNode, None, None),
|
59 |
+
(BooleanNode, "0", False),
|
60 |
+
(BooleanNode, 0, False),
|
61 |
+
# any
|
62 |
+
(AnyNode, 3, 3),
|
63 |
+
(AnyNode, 3.14, 3.14),
|
64 |
+
(AnyNode, False, False),
|
65 |
+
(AnyNode, Color.RED, Color.RED),
|
66 |
+
(AnyNode, None, None),
|
67 |
+
# Enum node
|
68 |
+
(lambda v: EnumNode(enum_type=Color, value=v), Color.RED, Color.RED),
|
69 |
+
(lambda v: EnumNode(enum_type=Color, value=v), "Color.RED", Color.RED),
|
70 |
+
(lambda v: EnumNode(enum_type=Color, value=v), "RED", Color.RED),
|
71 |
+
(lambda v: EnumNode(enum_type=Color, value=v), 1, Color.RED),
|
72 |
+
],
|
73 |
+
)
|
74 |
+
def test_valid_inputs(type_: type, input_: Any, output_: Any) -> None:
|
75 |
+
node = type_(input_)
|
76 |
+
assert node == output_
|
77 |
+
assert node == node
|
78 |
+
assert not (node != output_)
|
79 |
+
assert not (node != node)
|
80 |
+
assert str(node) == str(output_)
|
81 |
+
|
82 |
+
|
83 |
+
# testing invalid conversions
|
84 |
+
@pytest.mark.parametrize( # type: ignore
|
85 |
+
"type_,input_",
|
86 |
+
[
|
87 |
+
(IntegerNode, "abc"),
|
88 |
+
(IntegerNode, 10.1),
|
89 |
+
(IntegerNode, "-1132c"),
|
90 |
+
(FloatNode, "abc"),
|
91 |
+
(IntegerNode, "-abc"),
|
92 |
+
(BooleanNode, "Nope"),
|
93 |
+
(BooleanNode, "Yup"),
|
94 |
+
(StringNode, [1, 2]),
|
95 |
+
(StringNode, ListConfig([1, 2])),
|
96 |
+
(StringNode, {"foo": "var"}),
|
97 |
+
(FloatNode, DictConfig({"foo": "var"})),
|
98 |
+
(IntegerNode, [1, 2]),
|
99 |
+
(IntegerNode, ListConfig([1, 2])),
|
100 |
+
(IntegerNode, {"foo": "var"}),
|
101 |
+
(IntegerNode, DictConfig({"foo": "var"})),
|
102 |
+
(BooleanNode, [1, 2]),
|
103 |
+
(BooleanNode, ListConfig([1, 2])),
|
104 |
+
(BooleanNode, {"foo": "var"}),
|
105 |
+
(BooleanNode, DictConfig({"foo": "var"})),
|
106 |
+
(FloatNode, [1, 2]),
|
107 |
+
(FloatNode, ListConfig([1, 2])),
|
108 |
+
(FloatNode, {"foo": "var"}),
|
109 |
+
(FloatNode, DictConfig({"foo": "var"})),
|
110 |
+
(AnyNode, [1, 2]),
|
111 |
+
(AnyNode, ListConfig([1, 2])),
|
112 |
+
(AnyNode, {"foo": "var"}),
|
113 |
+
(AnyNode, DictConfig({"foo": "var"})),
|
114 |
+
(AnyNode, IllegalType()),
|
115 |
+
],
|
116 |
+
)
|
117 |
+
def test_invalid_inputs(type_: type, input_: Any) -> None:
|
118 |
+
empty_node = type_()
|
119 |
+
|
120 |
+
with pytest.raises(ValidationError):
|
121 |
+
empty_node._set_value(input_)
|
122 |
+
with pytest.raises(ValidationError):
|
123 |
+
type_(input_)
|
124 |
+
|
125 |
+
|
126 |
+
@pytest.mark.parametrize( # type: ignore
|
127 |
+
"input_, expected_type",
|
128 |
+
[
|
129 |
+
({}, DictConfig),
|
130 |
+
([], ListConfig),
|
131 |
+
(5, AnyNode),
|
132 |
+
(5.0, AnyNode),
|
133 |
+
(True, AnyNode),
|
134 |
+
(False, AnyNode),
|
135 |
+
("str", AnyNode),
|
136 |
+
],
|
137 |
+
)
|
138 |
+
def test_assigned_value_node_type(input_: type, expected_type: Any) -> None:
|
139 |
+
c = OmegaConf.create()
|
140 |
+
assert isinstance(c, DictConfig)
|
141 |
+
c.foo = input_
|
142 |
+
assert type(c._get_node("foo")) == expected_type
|
143 |
+
|
144 |
+
|
145 |
+
# dict
|
146 |
+
def test_dict_any() -> None:
|
147 |
+
c = OmegaConf.create()
|
148 |
+
assert isinstance(c, DictConfig)
|
149 |
+
# default type is Any
|
150 |
+
c.foo = 10
|
151 |
+
c[Enum1.FOO] = "bar"
|
152 |
+
|
153 |
+
assert c.foo == 10
|
154 |
+
assert type(c._get_node("foo")) == AnyNode
|
155 |
+
c.foo = "string"
|
156 |
+
assert c.foo == "string"
|
157 |
+
|
158 |
+
assert type(c._get_node(Enum1.FOO)) == AnyNode
|
159 |
+
|
160 |
+
|
161 |
+
def test_dict_integer_1() -> None:
|
162 |
+
c = OmegaConf.create()
|
163 |
+
assert isinstance(c, DictConfig)
|
164 |
+
c.foo = IntegerNode(10)
|
165 |
+
assert type(c._get_node("foo")) == IntegerNode
|
166 |
+
assert c.foo == 10
|
167 |
+
|
168 |
+
|
169 |
+
# list
|
170 |
+
def test_list_any() -> None:
|
171 |
+
c = OmegaConf.create([])
|
172 |
+
assert isinstance(c, ListConfig)
|
173 |
+
# default type is Any
|
174 |
+
c.append(10)
|
175 |
+
assert c[0] == 10
|
176 |
+
assert type(c._get_node(0)) == AnyNode
|
177 |
+
c[0] = "string"
|
178 |
+
assert c[0] == "string"
|
179 |
+
|
180 |
+
|
181 |
+
def test_list_integer() -> None:
|
182 |
+
val = 10
|
183 |
+
c = OmegaConf.create([])
|
184 |
+
assert isinstance(c, ListConfig)
|
185 |
+
c.append(IntegerNode(val))
|
186 |
+
assert type(c._get_node(0)) == IntegerNode
|
187 |
+
assert c.get(0) == val
|
188 |
+
|
189 |
+
|
190 |
+
def test_list_integer_rejects_string() -> None:
|
191 |
+
c = OmegaConf.create([])
|
192 |
+
assert isinstance(c, ListConfig)
|
193 |
+
c.append(IntegerNode(10))
|
194 |
+
assert c.get(0) == 10
|
195 |
+
with pytest.raises(ValidationError):
|
196 |
+
c[0] = "string"
|
197 |
+
assert c[0] == 10
|
198 |
+
assert type(c._get_node(0)) == IntegerNode
|
199 |
+
|
200 |
+
|
201 |
+
# Test merge raises validation error
|
202 |
+
@pytest.mark.parametrize( # type: ignore
|
203 |
+
"c1, c2",
|
204 |
+
[
|
205 |
+
(dict(a=IntegerNode(10)), dict(a="str")),
|
206 |
+
(dict(a=IntegerNode(10)), dict(a=StringNode("str"))),
|
207 |
+
(dict(a=10, b=IntegerNode(10)), dict(a=20, b="str")),
|
208 |
+
(dict(foo=dict(bar=IntegerNode(10))), dict(foo=dict(bar="str"))),
|
209 |
+
],
|
210 |
+
)
|
211 |
+
def test_merge_validation_error(c1: Dict[str, Any], c2: Dict[str, Any]) -> None:
|
212 |
+
conf1 = OmegaConf.create(c1)
|
213 |
+
conf2 = OmegaConf.create(c2)
|
214 |
+
with pytest.raises(ValidationError):
|
215 |
+
OmegaConf.merge(conf1, conf2)
|
216 |
+
# make sure that conf1 and conf2 were not modified
|
217 |
+
assert conf1 == OmegaConf.create(c1)
|
218 |
+
assert conf2 == OmegaConf.create(c2)
|
219 |
+
|
220 |
+
|
221 |
+
@pytest.mark.parametrize( # type: ignore
|
222 |
+
"type_,valid_value, invalid_value",
|
223 |
+
[
|
224 |
+
(IntegerNode, 1, "invalid"),
|
225 |
+
(FloatNode, 3.1415, "invalid"),
|
226 |
+
(BooleanNode, True, "invalid"),
|
227 |
+
(AnyNode, "aaa", None),
|
228 |
+
(StringNode, "blah", None),
|
229 |
+
],
|
230 |
+
)
|
231 |
+
def test_accepts_mandatory_missing(
|
232 |
+
type_: type, valid_value: Any, invalid_value: Any
|
233 |
+
) -> None:
|
234 |
+
node = type_()
|
235 |
+
node._set_value("???")
|
236 |
+
assert node._value() == "???"
|
237 |
+
|
238 |
+
conf = OmegaConf.create({"foo": node})
|
239 |
+
assert isinstance(conf, DictConfig)
|
240 |
+
assert "foo" not in conf
|
241 |
+
assert type(conf._get_node("foo")) == type_
|
242 |
+
|
243 |
+
conf.foo = valid_value
|
244 |
+
# make sure valid assignment does not change the type
|
245 |
+
assert type(conf._get_node("foo")) == type_
|
246 |
+
assert "foo" in conf
|
247 |
+
assert conf.foo == valid_value
|
248 |
+
|
249 |
+
if invalid_value is not None:
|
250 |
+
with pytest.raises(ValidationError):
|
251 |
+
conf.foo = invalid_value
|
252 |
+
|
253 |
+
|
254 |
+
class Enum1(Enum):
|
255 |
+
FOO = 1
|
256 |
+
BAR = 2
|
257 |
+
|
258 |
+
|
259 |
+
class Enum2(Enum):
|
260 |
+
NOT_FOO = 1
|
261 |
+
NOT_BAR = 2
|
262 |
+
|
263 |
+
|
264 |
+
@pytest.mark.parametrize( # type: ignore
|
265 |
+
"type_", [BooleanNode, EnumNode, FloatNode, IntegerNode, StringNode, AnyNode]
|
266 |
+
)
|
267 |
+
@pytest.mark.parametrize( # type: ignore
|
268 |
+
"values, success_map",
|
269 |
+
[
|
270 |
+
(
|
271 |
+
# True aliases
|
272 |
+
(True, "Y", "true", "yes", "on"),
|
273 |
+
{
|
274 |
+
"BooleanNode": True, # noqa F601
|
275 |
+
"StringNode": str, # noqa F601
|
276 |
+
"AnyNode": copy.copy, # noqa F601
|
277 |
+
},
|
278 |
+
),
|
279 |
+
(
|
280 |
+
("1", 1, 10, -10),
|
281 |
+
{
|
282 |
+
"BooleanNode": True, # noqa F601
|
283 |
+
"IntegerNode": int, # noqa F601
|
284 |
+
"FloatNode": float, # noqa F601
|
285 |
+
"StringNode": str, # noqa F601
|
286 |
+
"AnyNode": copy.copy, # noqa F601
|
287 |
+
},
|
288 |
+
),
|
289 |
+
(
|
290 |
+
# Floaty things
|
291 |
+
("1.0", 1.0, float("inf"), float("-inf"), "10e-3", 10e-3),
|
292 |
+
{"FloatNode": float, "StringNode": str, "AnyNode": copy.copy},
|
293 |
+
),
|
294 |
+
(
|
295 |
+
# False aliases
|
296 |
+
(False, "N", "false", "no", "off"),
|
297 |
+
{
|
298 |
+
"BooleanNode": False, # noqa F601
|
299 |
+
"StringNode": str, # noqa F601
|
300 |
+
"AnyNode": copy.copy, # noqa F601
|
301 |
+
},
|
302 |
+
),
|
303 |
+
(
|
304 |
+
# Falsy integers
|
305 |
+
("0", 0),
|
306 |
+
{
|
307 |
+
"BooleanNode": False, # noqa F601
|
308 |
+
"IntegerNode": 0, # noqa F601
|
309 |
+
"FloatNode": 0.0, # noqa F601
|
310 |
+
"StringNode": str, # noqa F601
|
311 |
+
"AnyNode": copy.copy, # noqa F601
|
312 |
+
},
|
313 |
+
),
|
314 |
+
],
|
315 |
+
)
|
316 |
+
def test_legal_assignment(
|
317 |
+
type_: type, values: Any, success_map: Dict[Any, Dict[str, Any]]
|
318 |
+
) -> None:
|
319 |
+
|
320 |
+
if not isinstance(values, (list, tuple)):
|
321 |
+
values = [values]
|
322 |
+
|
323 |
+
for value in values:
|
324 |
+
if type_.__name__ in success_map.keys():
|
325 |
+
expected = success_map[type_.__name__]
|
326 |
+
if callable(expected):
|
327 |
+
expected = expected(value)
|
328 |
+
node = type_(value)
|
329 |
+
assert node._value() == expected
|
330 |
+
else:
|
331 |
+
with pytest.raises(ValidationError):
|
332 |
+
type_(value)
|
333 |
+
|
334 |
+
|
335 |
+
@pytest.mark.parametrize( # type: ignore
|
336 |
+
"node,value",
|
337 |
+
[
|
338 |
+
(IntegerNode(), "foo"),
|
339 |
+
(BooleanNode(), "foo"),
|
340 |
+
(FloatNode(), "foo"),
|
341 |
+
(EnumNode(enum_type=Enum1), "foo"),
|
342 |
+
],
|
343 |
+
)
|
344 |
+
def test_illegal_assignment(node: ValueNode, value: Any) -> None:
|
345 |
+
with pytest.raises(ValidationError):
|
346 |
+
node._set_value(value)
|
347 |
+
|
348 |
+
|
349 |
+
@pytest.mark.parametrize( # type: ignore
|
350 |
+
"node_type", [BooleanNode, EnumNode, FloatNode, IntegerNode, StringNode, AnyNode]
|
351 |
+
)
|
352 |
+
@pytest.mark.parametrize( # type: ignore
|
353 |
+
"enum_type, values, success_map",
|
354 |
+
[
|
355 |
+
(
|
356 |
+
Enum1,
|
357 |
+
(Enum1.FOO, "Enum1.FOO", "FOO", 1),
|
358 |
+
{EnumNode: Enum1.FOO, AnyNode: copy.copy, StringNode: str},
|
359 |
+
)
|
360 |
+
],
|
361 |
+
)
|
362 |
+
def test_legal_assignment_enum(
|
363 |
+
node_type: Type[EnumNode],
|
364 |
+
enum_type: Type[Enum],
|
365 |
+
values: Tuple[Any],
|
366 |
+
success_map: Dict[Any, Any],
|
367 |
+
) -> None:
|
368 |
+
assert isinstance(values, (list, tuple))
|
369 |
+
|
370 |
+
for value in values:
|
371 |
+
if node_type in success_map.keys():
|
372 |
+
expected = success_map[node_type]
|
373 |
+
if callable(expected):
|
374 |
+
expected = expected(value)
|
375 |
+
node = node_type(enum_type)
|
376 |
+
node._set_value(value)
|
377 |
+
assert node._value() == expected
|
378 |
+
else:
|
379 |
+
with pytest.raises(ValidationError):
|
380 |
+
node_type(enum_type)
|
381 |
+
|
382 |
+
|
383 |
+
class DummyEnum(Enum):
|
384 |
+
FOO = 1
|
385 |
+
|
386 |
+
|
387 |
+
@pytest.mark.parametrize("is_optional", [True, False]) # type: ignore
|
388 |
+
@pytest.mark.parametrize( # type: ignore
|
389 |
+
"ref_type, type_, value, expected_type",
|
390 |
+
[
|
391 |
+
(Any, Any, 10, AnyNode),
|
392 |
+
(DummyEnum, DummyEnum, DummyEnum.FOO, EnumNode),
|
393 |
+
(int, int, 42, IntegerNode),
|
394 |
+
(float, float, 3.1415, FloatNode),
|
395 |
+
(bool, bool, True, BooleanNode),
|
396 |
+
(str, str, "foo", StringNode),
|
397 |
+
],
|
398 |
+
)
|
399 |
+
def test_node_wrap(
|
400 |
+
ref_type: type, type_: type, is_optional: bool, value: Any, expected_type: Any
|
401 |
+
) -> None:
|
402 |
+
from omegaconf.omegaconf import _node_wrap
|
403 |
+
|
404 |
+
ret = _node_wrap(
|
405 |
+
ref_type=Any,
|
406 |
+
type_=type_,
|
407 |
+
value=value,
|
408 |
+
is_optional=is_optional,
|
409 |
+
parent=None,
|
410 |
+
key=None,
|
411 |
+
)
|
412 |
+
assert ret._metadata.ref_type == ref_type
|
413 |
+
assert type(ret) == expected_type
|
414 |
+
assert ret == value
|
415 |
+
|
416 |
+
if is_optional:
|
417 |
+
ret = _node_wrap(
|
418 |
+
ref_type=Any,
|
419 |
+
type_=type_,
|
420 |
+
value=None,
|
421 |
+
is_optional=is_optional,
|
422 |
+
parent=None,
|
423 |
+
key=None,
|
424 |
+
)
|
425 |
+
assert type(ret) == expected_type
|
426 |
+
# noinspection PyComparisonWithNone
|
427 |
+
assert ret == None # noqa E711
|
428 |
+
|
429 |
+
|
430 |
+
def test_node_wrap_illegal_type() -> None:
|
431 |
+
class UserClass:
|
432 |
+
pass
|
433 |
+
|
434 |
+
from omegaconf.omegaconf import _node_wrap
|
435 |
+
|
436 |
+
with pytest.raises(ValidationError):
|
437 |
+
_node_wrap(
|
438 |
+
type_=UserClass, value=UserClass(), is_optional=False, parent=None, key=None
|
439 |
+
)
|
440 |
+
|
441 |
+
|
442 |
+
@pytest.mark.parametrize( # type: ignore
|
443 |
+
"obj",
|
444 |
+
[
|
445 |
+
StringNode(),
|
446 |
+
StringNode(value="foo"),
|
447 |
+
StringNode(value="foo", is_optional=False),
|
448 |
+
BooleanNode(value=True),
|
449 |
+
IntegerNode(value=10),
|
450 |
+
FloatNode(value=10.0),
|
451 |
+
OmegaConf.create({}),
|
452 |
+
OmegaConf.create([]),
|
453 |
+
OmegaConf.create({"foo": "foo"}),
|
454 |
+
],
|
455 |
+
)
|
456 |
+
def test_deepcopy(obj: Any) -> None:
|
457 |
+
cp = copy.deepcopy(obj)
|
458 |
+
assert cp == obj
|
459 |
+
assert id(cp) != id(obj)
|
460 |
+
assert obj.__dict__.keys() == cp.__dict__.keys()
|
461 |
+
for k in obj.__dict__.keys():
|
462 |
+
assert obj.__dict__[k] == cp.__dict__[k]
|
463 |
+
|
464 |
+
|
465 |
+
@pytest.mark.parametrize( # type: ignore
|
466 |
+
"node, value, expected",
|
467 |
+
[
|
468 |
+
(StringNode(), None, True),
|
469 |
+
(StringNode(), 100, False),
|
470 |
+
(StringNode("foo"), "foo", True),
|
471 |
+
(IntegerNode(), 1, False),
|
472 |
+
(IntegerNode(1), 1, True),
|
473 |
+
(IntegerNode(1), "foo", False),
|
474 |
+
(FloatNode(), 1, False),
|
475 |
+
(FloatNode(), None, True),
|
476 |
+
(FloatNode(1.0), None, False),
|
477 |
+
(FloatNode(1.0), 1.0, True),
|
478 |
+
(FloatNode(1), 1, True),
|
479 |
+
(FloatNode(1.0), "foo", False),
|
480 |
+
(BooleanNode(), True, False),
|
481 |
+
(BooleanNode(), False, False),
|
482 |
+
(BooleanNode(), None, True),
|
483 |
+
(BooleanNode(True), None, False),
|
484 |
+
(BooleanNode(True), False, False),
|
485 |
+
(BooleanNode(False), False, True),
|
486 |
+
(AnyNode(value=1, is_optional=True), AnyNode(value=1, is_optional=True), True),
|
487 |
+
(
|
488 |
+
AnyNode(value=1, is_optional=True),
|
489 |
+
AnyNode(value=1, is_optional=False),
|
490 |
+
True,
|
491 |
+
),
|
492 |
+
(EnumNode(enum_type=Enum1), Enum1.BAR, False),
|
493 |
+
(EnumNode(enum_type=Enum1), EnumNode(Enum1), True),
|
494 |
+
(EnumNode(enum_type=Enum1), "nope", False),
|
495 |
+
(
|
496 |
+
EnumNode(enum_type=Enum1, value=Enum1.BAR),
|
497 |
+
EnumNode(enum_type=Enum1, value=Enum1.BAR),
|
498 |
+
True,
|
499 |
+
),
|
500 |
+
(EnumNode(enum_type=Enum1, value=Enum1.BAR), Enum1.BAR, True),
|
501 |
+
],
|
502 |
+
)
|
503 |
+
def test_eq(node: ValueNode, value: Any, expected: Any) -> None:
|
504 |
+
assert (node == value) == expected
|
505 |
+
assert (node != value) != expected
|
506 |
+
assert (value == node) == expected
|
507 |
+
assert (value != node) != expected
|
508 |
+
assert (node.__hash__() == value.__hash__()) == expected
|
509 |
+
|
510 |
+
|
511 |
+
@pytest.mark.parametrize("value", [1, 3.14, True, None, Enum1.FOO]) # type: ignore
|
512 |
+
def test_set_anynode_with_primitive_type(value: Any) -> None:
|
513 |
+
cfg = OmegaConf.create({"a": 5})
|
514 |
+
a_before = cfg._get_node("a")
|
515 |
+
cfg.a = value
|
516 |
+
# changing anynode's value with a primitive type should set value
|
517 |
+
assert id(cfg._get_node("a")) == id(a_before)
|
518 |
+
assert cfg.a == value
|
519 |
+
|
520 |
+
|
521 |
+
@pytest.mark.parametrize( # type: ignore
|
522 |
+
"value, container_type",
|
523 |
+
[
|
524 |
+
(ListConfig(content=[1, 2]), ListConfig),
|
525 |
+
([1, 2], ListConfig),
|
526 |
+
(DictConfig(content={"foo": "var"}), DictConfig),
|
527 |
+
({"foo": "var"}, DictConfig),
|
528 |
+
],
|
529 |
+
)
|
530 |
+
def test_set_anynode_with_container(value: Any, container_type: Any) -> None:
|
531 |
+
cfg = OmegaConf.create({"a": 5})
|
532 |
+
a_before = cfg._get_node("a")
|
533 |
+
cfg.a = value
|
534 |
+
# changing anynode's value with a container should wrap a new node
|
535 |
+
assert id(cfg._get_node("a")) != id(a_before)
|
536 |
+
assert isinstance(cfg.a, container_type)
|
537 |
+
assert cfg.a == value
|
538 |
+
|
539 |
+
|
540 |
+
def test_set_anynode_with_illegal_type() -> None:
|
541 |
+
cfg = OmegaConf.create({"a": 5})
|
542 |
+
with pytest.raises(ValidationError):
|
543 |
+
cfg.a = IllegalType()
|
544 |
+
|
545 |
+
|
546 |
+
def test_set_valuenode() -> None:
|
547 |
+
cfg = OmegaConf.structured(User)
|
548 |
+
a_before = cfg._get_node("age")
|
549 |
+
cfg.age = 12
|
550 |
+
assert id(cfg._get_node("age")) == id(a_before)
|
551 |
+
with pytest.raises(ValidationError):
|
552 |
+
cfg.age = []
|
tests/test_omegaconf.py
ADDED
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any
|
2 |
+
|
3 |
+
import pytest
|
4 |
+
from pytest import raises
|
5 |
+
|
6 |
+
from omegaconf import (
|
7 |
+
MISSING,
|
8 |
+
BooleanNode,
|
9 |
+
DictConfig,
|
10 |
+
EnumNode,
|
11 |
+
FloatNode,
|
12 |
+
IntegerNode,
|
13 |
+
ListConfig,
|
14 |
+
MissingMandatoryValue,
|
15 |
+
OmegaConf,
|
16 |
+
StringNode,
|
17 |
+
)
|
18 |
+
from omegaconf.errors import UnsupportedInterpolationType
|
19 |
+
|
20 |
+
from . import Color, ConcretePlugin, IllegalType, StructuredWithMissing, does_not_raise
|
21 |
+
|
22 |
+
|
23 |
+
@pytest.mark.parametrize( # type: ignore
|
24 |
+
"cfg, key, expected_is_missing, expectation",
|
25 |
+
[
|
26 |
+
({}, "foo", False, does_not_raise()),
|
27 |
+
({"foo": True}, "foo", False, does_not_raise()),
|
28 |
+
({"foo": MISSING}, "foo", True, raises(MissingMandatoryValue)),
|
29 |
+
(
|
30 |
+
{"foo": "${bar}", "bar": MISSING},
|
31 |
+
"foo",
|
32 |
+
True,
|
33 |
+
raises(MissingMandatoryValue),
|
34 |
+
),
|
35 |
+
(
|
36 |
+
{"foo": "${unknown_resolver:foo}"},
|
37 |
+
"foo",
|
38 |
+
False,
|
39 |
+
raises(UnsupportedInterpolationType),
|
40 |
+
),
|
41 |
+
({"foo": StringNode(value="???")}, "foo", True, raises(MissingMandatoryValue)),
|
42 |
+
(
|
43 |
+
{"foo": StringNode(value="???"), "inter": "${foo}"},
|
44 |
+
"inter",
|
45 |
+
True,
|
46 |
+
raises(MissingMandatoryValue),
|
47 |
+
),
|
48 |
+
(StructuredWithMissing, "num", True, raises(MissingMandatoryValue)),
|
49 |
+
(StructuredWithMissing, "opt_num", True, raises(MissingMandatoryValue)),
|
50 |
+
(StructuredWithMissing, "dict", True, raises(MissingMandatoryValue)),
|
51 |
+
(StructuredWithMissing, "opt_dict", True, raises(MissingMandatoryValue)),
|
52 |
+
(StructuredWithMissing, "list", True, raises(MissingMandatoryValue)),
|
53 |
+
(StructuredWithMissing, "opt_list", True, raises(MissingMandatoryValue)),
|
54 |
+
(StructuredWithMissing, "user", True, raises(MissingMandatoryValue)),
|
55 |
+
(StructuredWithMissing, "opt_user", True, raises(MissingMandatoryValue)),
|
56 |
+
(StructuredWithMissing, "inter_user", True, raises(MissingMandatoryValue)),
|
57 |
+
(StructuredWithMissing, "inter_opt_user", True, raises(MissingMandatoryValue)),
|
58 |
+
(StructuredWithMissing, "inter_num", True, raises(MissingMandatoryValue)),
|
59 |
+
],
|
60 |
+
)
|
61 |
+
def test_is_missing(
|
62 |
+
cfg: Any, key: str, expected_is_missing: bool, expectation: Any
|
63 |
+
) -> None:
|
64 |
+
cfg = OmegaConf.create(cfg)
|
65 |
+
with expectation:
|
66 |
+
cfg.get(key)
|
67 |
+
|
68 |
+
assert OmegaConf.is_missing(cfg, key) == expected_is_missing
|
69 |
+
OmegaConf.set_struct(cfg, True)
|
70 |
+
assert OmegaConf.is_missing(cfg, key) == expected_is_missing
|
71 |
+
OmegaConf.set_readonly(cfg, True)
|
72 |
+
assert OmegaConf.is_missing(cfg, key) == expected_is_missing
|
73 |
+
|
74 |
+
|
75 |
+
def test_is_missing_resets() -> None:
|
76 |
+
cfg = OmegaConf.structured(StructuredWithMissing)
|
77 |
+
assert OmegaConf.is_missing(cfg, "dict")
|
78 |
+
cfg.dict = {}
|
79 |
+
assert not OmegaConf.is_missing(cfg, "dict")
|
80 |
+
|
81 |
+
assert OmegaConf.is_missing(cfg, "list")
|
82 |
+
cfg.list = [1, 2, 3]
|
83 |
+
assert not OmegaConf.is_missing(cfg, "list")
|
84 |
+
cfg.list = "???"
|
85 |
+
assert OmegaConf.is_missing(cfg, "list")
|
86 |
+
|
87 |
+
|
88 |
+
@pytest.mark.parametrize( # type: ignore
|
89 |
+
"cfg, expected",
|
90 |
+
[
|
91 |
+
(None, False),
|
92 |
+
({}, False),
|
93 |
+
([], False),
|
94 |
+
("aa", False),
|
95 |
+
(10, False),
|
96 |
+
(True, False),
|
97 |
+
(bool, False),
|
98 |
+
(StringNode("foo"), False),
|
99 |
+
(ConcretePlugin, False),
|
100 |
+
(ConcretePlugin(), False),
|
101 |
+
(OmegaConf.create({}), True),
|
102 |
+
(OmegaConf.create([]), True),
|
103 |
+
(OmegaConf.structured(ConcretePlugin), True),
|
104 |
+
(OmegaConf.structured(ConcretePlugin()), True),
|
105 |
+
],
|
106 |
+
)
|
107 |
+
def test_is_config(cfg: Any, expected: bool) -> None:
|
108 |
+
assert OmegaConf.is_config(cfg) == expected
|
109 |
+
|
110 |
+
|
111 |
+
@pytest.mark.parametrize( # type: ignore
|
112 |
+
"cfg, expected",
|
113 |
+
[
|
114 |
+
(None, False),
|
115 |
+
({}, False),
|
116 |
+
([], False),
|
117 |
+
("aa", False),
|
118 |
+
(10, False),
|
119 |
+
(True, False),
|
120 |
+
(bool, False),
|
121 |
+
(StringNode("foo"), False),
|
122 |
+
(ConcretePlugin, False),
|
123 |
+
(ConcretePlugin(), False),
|
124 |
+
(OmegaConf.create({}), False),
|
125 |
+
(OmegaConf.create([]), True),
|
126 |
+
(OmegaConf.structured(ConcretePlugin), False),
|
127 |
+
(OmegaConf.structured(ConcretePlugin()), False),
|
128 |
+
],
|
129 |
+
)
|
130 |
+
def test_is_list(cfg: Any, expected: bool) -> None:
|
131 |
+
assert OmegaConf.is_list(cfg) == expected
|
132 |
+
|
133 |
+
|
134 |
+
@pytest.mark.parametrize( # type: ignore
|
135 |
+
"cfg, expected",
|
136 |
+
[
|
137 |
+
(None, False),
|
138 |
+
({}, False),
|
139 |
+
([], False),
|
140 |
+
("aa", False),
|
141 |
+
(10, False),
|
142 |
+
(True, False),
|
143 |
+
(bool, False),
|
144 |
+
(StringNode("foo"), False),
|
145 |
+
(ConcretePlugin, False),
|
146 |
+
(ConcretePlugin(), False),
|
147 |
+
(OmegaConf.create({}), True),
|
148 |
+
(OmegaConf.create([]), False),
|
149 |
+
(OmegaConf.structured(ConcretePlugin), True),
|
150 |
+
(OmegaConf.structured(ConcretePlugin()), True),
|
151 |
+
],
|
152 |
+
)
|
153 |
+
def test_is_dict(cfg: Any, expected: bool) -> None:
|
154 |
+
assert OmegaConf.is_dict(cfg) == expected
|
155 |
+
|
156 |
+
|
157 |
+
@pytest.mark.parametrize("is_optional", [True, False]) # type: ignore
|
158 |
+
@pytest.mark.parametrize( # type: ignore
|
159 |
+
"fac",
|
160 |
+
[
|
161 |
+
(
|
162 |
+
lambda is_optional, missing: StringNode(
|
163 |
+
value="foo" if not missing else "???", is_optional=is_optional
|
164 |
+
)
|
165 |
+
),
|
166 |
+
(
|
167 |
+
lambda is_optional, missing: IntegerNode(
|
168 |
+
value=10 if not missing else "???", is_optional=is_optional
|
169 |
+
)
|
170 |
+
),
|
171 |
+
(
|
172 |
+
lambda is_optional, missing: FloatNode(
|
173 |
+
value=10 if not missing else "???", is_optional=is_optional
|
174 |
+
)
|
175 |
+
),
|
176 |
+
(
|
177 |
+
lambda is_optional, missing: BooleanNode(
|
178 |
+
value=True if not missing else "???", is_optional=is_optional
|
179 |
+
)
|
180 |
+
),
|
181 |
+
(
|
182 |
+
lambda is_optional, missing: EnumNode(
|
183 |
+
enum_type=Color,
|
184 |
+
value=Color.RED if not missing else "???",
|
185 |
+
is_optional=is_optional,
|
186 |
+
)
|
187 |
+
),
|
188 |
+
(
|
189 |
+
lambda is_optional, missing: ListConfig(
|
190 |
+
content=[1, 2, 3] if not missing else "???", is_optional=is_optional
|
191 |
+
)
|
192 |
+
),
|
193 |
+
(
|
194 |
+
lambda is_optional, missing: DictConfig(
|
195 |
+
content={"foo": "bar"} if not missing else "???",
|
196 |
+
is_optional=is_optional,
|
197 |
+
)
|
198 |
+
),
|
199 |
+
(
|
200 |
+
lambda is_optional, missing: DictConfig(
|
201 |
+
ref_type=ConcretePlugin,
|
202 |
+
content=ConcretePlugin() if not missing else "???",
|
203 |
+
is_optional=is_optional,
|
204 |
+
)
|
205 |
+
),
|
206 |
+
],
|
207 |
+
)
|
208 |
+
def test_is_optional(fac: Any, is_optional: bool) -> None:
|
209 |
+
obj = fac(is_optional, False)
|
210 |
+
assert OmegaConf.is_optional(obj) == is_optional
|
211 |
+
|
212 |
+
cfg = OmegaConf.create({"node": obj})
|
213 |
+
assert OmegaConf.is_optional(cfg, "node") == is_optional
|
214 |
+
|
215 |
+
obj = fac(is_optional, True)
|
216 |
+
assert OmegaConf.is_optional(obj) == is_optional
|
217 |
+
|
218 |
+
cfg = OmegaConf.create({"node": obj})
|
219 |
+
assert OmegaConf.is_optional(cfg, "node") == is_optional
|
220 |
+
|
221 |
+
|
222 |
+
@pytest.mark.parametrize("is_none", [True, False]) # type: ignore
|
223 |
+
@pytest.mark.parametrize( # type: ignore
|
224 |
+
"fac",
|
225 |
+
[
|
226 |
+
(lambda none: StringNode(value="foo" if not none else None, is_optional=True)),
|
227 |
+
(lambda none: IntegerNode(value=10 if not none else None, is_optional=True)),
|
228 |
+
(lambda none: FloatNode(value=10 if not none else None, is_optional=True)),
|
229 |
+
(lambda none: BooleanNode(value=True if not none else None, is_optional=True)),
|
230 |
+
(
|
231 |
+
lambda none: EnumNode(
|
232 |
+
enum_type=Color,
|
233 |
+
value=Color.RED if not none else None,
|
234 |
+
is_optional=True,
|
235 |
+
)
|
236 |
+
),
|
237 |
+
(
|
238 |
+
lambda none: ListConfig(
|
239 |
+
content=[1, 2, 3] if not none else None, is_optional=True
|
240 |
+
)
|
241 |
+
),
|
242 |
+
(
|
243 |
+
lambda none: DictConfig(
|
244 |
+
content={"foo": "bar"} if not none else None, is_optional=True
|
245 |
+
)
|
246 |
+
),
|
247 |
+
(
|
248 |
+
lambda none: DictConfig(
|
249 |
+
ref_type=ConcretePlugin,
|
250 |
+
content=ConcretePlugin() if not none else None,
|
251 |
+
is_optional=True,
|
252 |
+
)
|
253 |
+
),
|
254 |
+
],
|
255 |
+
)
|
256 |
+
def test_is_none(fac: Any, is_none: bool) -> None:
|
257 |
+
obj = fac(is_none)
|
258 |
+
assert OmegaConf.is_none(obj) == is_none
|
259 |
+
|
260 |
+
cfg = OmegaConf.create({"node": obj})
|
261 |
+
assert OmegaConf.is_none(cfg, "node") == is_none
|
262 |
+
|
263 |
+
|
264 |
+
@pytest.mark.parametrize(
|
265 |
+
"fac", # type: ignore
|
266 |
+
[
|
267 |
+
(
|
268 |
+
lambda inter: StringNode(
|
269 |
+
value="foo" if inter is None else inter, is_optional=True
|
270 |
+
)
|
271 |
+
),
|
272 |
+
(
|
273 |
+
lambda inter: IntegerNode(
|
274 |
+
value=10 if inter is None else inter, is_optional=True
|
275 |
+
)
|
276 |
+
),
|
277 |
+
(
|
278 |
+
lambda inter: FloatNode(
|
279 |
+
value=10 if inter is None else inter, is_optional=True
|
280 |
+
)
|
281 |
+
),
|
282 |
+
(
|
283 |
+
lambda inter: BooleanNode(
|
284 |
+
value=True if inter is None else inter, is_optional=True
|
285 |
+
)
|
286 |
+
),
|
287 |
+
(
|
288 |
+
lambda inter: EnumNode(
|
289 |
+
enum_type=Color,
|
290 |
+
value=Color.RED if inter is None else inter,
|
291 |
+
is_optional=True,
|
292 |
+
)
|
293 |
+
),
|
294 |
+
(
|
295 |
+
lambda inter: ListConfig(
|
296 |
+
content=[1, 2, 3] if inter is None else inter, is_optional=True
|
297 |
+
)
|
298 |
+
),
|
299 |
+
(
|
300 |
+
lambda inter: DictConfig(
|
301 |
+
content={"foo": "bar"} if inter is None else inter, is_optional=True
|
302 |
+
)
|
303 |
+
),
|
304 |
+
(
|
305 |
+
lambda inter: DictConfig(
|
306 |
+
ref_type=ConcretePlugin,
|
307 |
+
content=ConcretePlugin() if inter is None else inter,
|
308 |
+
is_optional=True,
|
309 |
+
)
|
310 |
+
),
|
311 |
+
],
|
312 |
+
ids=[
|
313 |
+
"StringNode",
|
314 |
+
"IntegerNode",
|
315 |
+
"FloatNode",
|
316 |
+
"BooleanNode",
|
317 |
+
"EnumNode",
|
318 |
+
"ListConfig",
|
319 |
+
"DictConfig",
|
320 |
+
"ConcretePlugin",
|
321 |
+
],
|
322 |
+
)
|
323 |
+
def test_is_interpolation(fac):
|
324 |
+
obj = fac(inter=None)
|
325 |
+
assert not OmegaConf.is_interpolation(obj)
|
326 |
+
cfg = OmegaConf.create({"node": obj})
|
327 |
+
assert not OmegaConf.is_interpolation(cfg, "node")
|
328 |
+
|
329 |
+
assert not OmegaConf.is_interpolation(cfg, "missing")
|
330 |
+
|
331 |
+
for inter in ["${foo}", "http://${url}", "${resolver:value}"]:
|
332 |
+
obj = fac(inter=inter)
|
333 |
+
assert OmegaConf.is_interpolation(obj)
|
334 |
+
cfg = OmegaConf.create({"node": obj})
|
335 |
+
assert OmegaConf.is_interpolation(cfg, "node")
|
336 |
+
|
337 |
+
|
338 |
+
@pytest.mark.parametrize( # type: ignore
|
339 |
+
"cfg, type_",
|
340 |
+
[
|
341 |
+
({"foo": 10}, int),
|
342 |
+
({"foo": 10.0}, float),
|
343 |
+
({"foo": True}, bool),
|
344 |
+
({"foo": "bar"}, str),
|
345 |
+
({"foo": None}, type(None)),
|
346 |
+
({"foo": ConcretePlugin()}, ConcretePlugin),
|
347 |
+
({"foo": ConcretePlugin}, ConcretePlugin),
|
348 |
+
({"foo": {}}, dict),
|
349 |
+
({"foo": OmegaConf.create()}, dict),
|
350 |
+
({"foo": []}, list),
|
351 |
+
({"foo": OmegaConf.create([])}, list),
|
352 |
+
],
|
353 |
+
)
|
354 |
+
def test_get_type(cfg: Any, type_: Any) -> None:
|
355 |
+
cfg = OmegaConf.create(cfg)
|
356 |
+
assert OmegaConf.get_type(cfg, "foo") == type_
|
357 |
+
|
358 |
+
|
359 |
+
@pytest.mark.parametrize( # type: ignore
|
360 |
+
"obj, type_",
|
361 |
+
[
|
362 |
+
(10, int),
|
363 |
+
(10.0, float),
|
364 |
+
(True, bool),
|
365 |
+
("foo", str),
|
366 |
+
(DictConfig(content={}), dict),
|
367 |
+
(ListConfig(content=[]), list),
|
368 |
+
(IllegalType, IllegalType),
|
369 |
+
(IllegalType(), IllegalType),
|
370 |
+
],
|
371 |
+
)
|
372 |
+
def test_get_type_on_raw(obj: Any, type_: Any) -> None:
|
373 |
+
assert OmegaConf.get_type(obj) == type_
|
374 |
+
|
375 |
+
|
376 |
+
def test_is_issubclass() -> None:
|
377 |
+
cfg = OmegaConf.structured(ConcretePlugin)
|
378 |
+
t = OmegaConf.get_type(cfg)
|
379 |
+
assert t is not None and issubclass(t, ConcretePlugin)
|
tests/test_readonly.py
ADDED
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from typing import Any, Callable, Dict, List, Union
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
from pytest import raises
|
6 |
+
|
7 |
+
from omegaconf import DictConfig, ListConfig, OmegaConf, ReadonlyConfigError
|
8 |
+
|
9 |
+
|
10 |
+
@pytest.mark.parametrize( # type: ignore
|
11 |
+
"src, func, expectation",
|
12 |
+
[
|
13 |
+
pytest.param(
|
14 |
+
{},
|
15 |
+
lambda c: c.__setitem__("a", 1),
|
16 |
+
raises(ReadonlyConfigError, match="a"),
|
17 |
+
id="dict_setitem",
|
18 |
+
),
|
19 |
+
pytest.param(
|
20 |
+
{"a": {"b": {"c": 1}}},
|
21 |
+
lambda c: c.__getattr__("a").__getattr__("b").__setitem__("c", 1),
|
22 |
+
raises(ReadonlyConfigError, match="a.b.c"),
|
23 |
+
id="dict_nested_setitem",
|
24 |
+
),
|
25 |
+
pytest.param(
|
26 |
+
{},
|
27 |
+
lambda c: OmegaConf.update(c, "a.b", 10, merge=True),
|
28 |
+
raises(ReadonlyConfigError, match="a"),
|
29 |
+
id="dict_update",
|
30 |
+
),
|
31 |
+
pytest.param(
|
32 |
+
{"a": 10},
|
33 |
+
lambda c: c.__setattr__("a", 1),
|
34 |
+
raises(ReadonlyConfigError, match="a"),
|
35 |
+
id="dict_setattr",
|
36 |
+
),
|
37 |
+
pytest.param(
|
38 |
+
{"a": 10},
|
39 |
+
lambda c: c.pop("a"),
|
40 |
+
raises(ReadonlyConfigError, match="a"),
|
41 |
+
id="dict_pop",
|
42 |
+
),
|
43 |
+
pytest.param(
|
44 |
+
{"a": 10},
|
45 |
+
lambda c: c.__delitem__("a"),
|
46 |
+
raises(ReadonlyConfigError, match="a"),
|
47 |
+
id="dict_delitem",
|
48 |
+
),
|
49 |
+
# list
|
50 |
+
pytest.param(
|
51 |
+
[],
|
52 |
+
lambda c: c.__setitem__(0, 1),
|
53 |
+
raises(ReadonlyConfigError, match="0"),
|
54 |
+
id="list_setitem",
|
55 |
+
),
|
56 |
+
pytest.param(
|
57 |
+
[],
|
58 |
+
lambda c: OmegaConf.update(c, "0.b", 10, merge=True),
|
59 |
+
raises(ReadonlyConfigError, match="[0]"),
|
60 |
+
id="list_update",
|
61 |
+
),
|
62 |
+
pytest.param(
|
63 |
+
[10], lambda c: c.pop(), raises(ReadonlyConfigError), id="list_pop"
|
64 |
+
),
|
65 |
+
pytest.param(
|
66 |
+
[0],
|
67 |
+
lambda c: c.__delitem__(0),
|
68 |
+
raises(ReadonlyConfigError, match="[0]"),
|
69 |
+
id="list_delitem",
|
70 |
+
),
|
71 |
+
],
|
72 |
+
)
|
73 |
+
def test_readonly(
|
74 |
+
src: Union[Dict[str, Any], List[Any]], func: Callable[[Any], Any], expectation: Any
|
75 |
+
) -> None:
|
76 |
+
c = OmegaConf.create(src)
|
77 |
+
OmegaConf.set_readonly(c, True)
|
78 |
+
with expectation:
|
79 |
+
func(c)
|
80 |
+
assert c == src
|
81 |
+
|
82 |
+
|
83 |
+
@pytest.mark.parametrize("src", [{}, []]) # type: ignore
|
84 |
+
def test_readonly_flag(src: Union[Dict[str, Any], List[Any]]) -> None:
|
85 |
+
c = OmegaConf.create(src)
|
86 |
+
assert not OmegaConf.is_readonly(c)
|
87 |
+
OmegaConf.set_readonly(c, True)
|
88 |
+
assert OmegaConf.is_readonly(c)
|
89 |
+
OmegaConf.set_readonly(c, False)
|
90 |
+
assert not OmegaConf.is_readonly(c)
|
91 |
+
OmegaConf.set_readonly(c, None)
|
92 |
+
assert not OmegaConf.is_readonly(c)
|
93 |
+
|
94 |
+
|
95 |
+
def test_readonly_nested_list() -> None:
|
96 |
+
c = OmegaConf.create([[1]])
|
97 |
+
assert isinstance(c, ListConfig)
|
98 |
+
assert not OmegaConf.is_readonly(c)
|
99 |
+
assert not OmegaConf.is_readonly(c[0])
|
100 |
+
OmegaConf.set_readonly(c, True)
|
101 |
+
assert OmegaConf.is_readonly(c)
|
102 |
+
assert OmegaConf.is_readonly(c[0])
|
103 |
+
OmegaConf.set_readonly(c, False)
|
104 |
+
assert not OmegaConf.is_readonly(c)
|
105 |
+
assert not OmegaConf.is_readonly(c[0])
|
106 |
+
OmegaConf.set_readonly(c, None)
|
107 |
+
assert not OmegaConf.is_readonly(c)
|
108 |
+
assert not OmegaConf.is_readonly(c[0])
|
109 |
+
OmegaConf.set_readonly(c[0], True)
|
110 |
+
assert not OmegaConf.is_readonly(c)
|
111 |
+
assert OmegaConf.is_readonly(c[0])
|
112 |
+
|
113 |
+
|
114 |
+
def test_readonly_list_insert() -> None:
|
115 |
+
c = OmegaConf.create([])
|
116 |
+
OmegaConf.set_readonly(c, True)
|
117 |
+
with raises(ReadonlyConfigError, match="[0]"):
|
118 |
+
c.insert(0, 10)
|
119 |
+
assert c == []
|
120 |
+
|
121 |
+
|
122 |
+
def test_readonly_list_insert_deep() -> None:
|
123 |
+
src: List[Dict[str, Any]] = [dict(a=[dict(b=[])])]
|
124 |
+
c = OmegaConf.create(src)
|
125 |
+
assert isinstance(c, ListConfig)
|
126 |
+
OmegaConf.set_readonly(c, True)
|
127 |
+
with raises(ReadonlyConfigError, match=re.escape("[0].a[0].b[0]")):
|
128 |
+
c[0].a[0].b.insert(0, 10)
|
129 |
+
assert c == src
|
130 |
+
|
131 |
+
|
132 |
+
def test_readonly_list_append() -> None:
|
133 |
+
c = OmegaConf.create([])
|
134 |
+
OmegaConf.set_readonly(c, True)
|
135 |
+
with raises(ReadonlyConfigError, match="[0]"):
|
136 |
+
c.append(10)
|
137 |
+
assert c == []
|
138 |
+
|
139 |
+
|
140 |
+
def test_readonly_list_change_item() -> None:
|
141 |
+
c = OmegaConf.create([1, 2, 3])
|
142 |
+
assert isinstance(c, ListConfig)
|
143 |
+
OmegaConf.set_readonly(c, True)
|
144 |
+
with raises(ReadonlyConfigError, match="[1]"):
|
145 |
+
c[1] = 10
|
146 |
+
assert c == [1, 2, 3]
|
147 |
+
|
148 |
+
|
149 |
+
def test_readonly_list_pop() -> None:
|
150 |
+
c = OmegaConf.create([1, 2, 3])
|
151 |
+
assert isinstance(c, ListConfig)
|
152 |
+
OmegaConf.set_readonly(c, True)
|
153 |
+
with raises(ReadonlyConfigError, match="[1]"):
|
154 |
+
c.pop(1)
|
155 |
+
assert c == [1, 2, 3]
|
156 |
+
|
157 |
+
|
158 |
+
def test_readonly_list_del() -> None:
|
159 |
+
c = OmegaConf.create([1, 2, 3])
|
160 |
+
assert isinstance(c, ListConfig)
|
161 |
+
OmegaConf.set_readonly(c, True)
|
162 |
+
with raises(ReadonlyConfigError, match="[1]"):
|
163 |
+
del c[1]
|
164 |
+
assert c == [1, 2, 3]
|
165 |
+
|
166 |
+
|
167 |
+
def test_readonly_list_sort() -> None:
|
168 |
+
c = OmegaConf.create([3, 1, 2])
|
169 |
+
assert isinstance(c, ListConfig)
|
170 |
+
OmegaConf.set_readonly(c, True)
|
171 |
+
with raises(ReadonlyConfigError):
|
172 |
+
c.sort()
|
173 |
+
assert c == [3, 1, 2]
|
174 |
+
|
175 |
+
|
176 |
+
def test_readonly_from_cli() -> None:
|
177 |
+
c = OmegaConf.create({"foo": {"bar": [1]}})
|
178 |
+
assert isinstance(c, DictConfig)
|
179 |
+
OmegaConf.set_readonly(c, True)
|
180 |
+
cli = OmegaConf.from_dotlist(["foo.bar=[2]"])
|
181 |
+
cfg2 = OmegaConf.merge(c, cli)
|
182 |
+
assert OmegaConf.is_readonly(c)
|
183 |
+
assert OmegaConf.is_readonly(cfg2)
|
184 |
+
|
185 |
+
|
186 |
+
@pytest.mark.parametrize( # type: ignore
|
187 |
+
"cfg1, cfg2",
|
188 |
+
[
|
189 |
+
pytest.param({"foo": {"bar": 10}}, {"foo": {"bar": 20}}, id="override_value"),
|
190 |
+
pytest.param({"foo": {"bar": 10}}, {"foo": {"yup": 20}}, id="adding_key"),
|
191 |
+
pytest.param({"a": 1}, {"b": 2}, id="adding_key"),
|
192 |
+
pytest.param({"a": 1}, OmegaConf.create({"b": 2}), id="adding_key"),
|
193 |
+
],
|
194 |
+
)
|
195 |
+
def test_merge_with_readonly(cfg1: Dict[str, Any], cfg2: Dict[str, Any]) -> None:
|
196 |
+
c = OmegaConf.create(cfg1)
|
197 |
+
OmegaConf.set_readonly(c, True)
|
198 |
+
with raises(ReadonlyConfigError):
|
199 |
+
c.merge_with(cfg2)
|
200 |
+
|
201 |
+
|
202 |
+
@pytest.mark.parametrize( # type: ignore
|
203 |
+
"readonly_key, cfg1, cfg2, expected",
|
204 |
+
[
|
205 |
+
pytest.param(
|
206 |
+
"",
|
207 |
+
{"foo": {"bar": 10}},
|
208 |
+
{"foo": {}},
|
209 |
+
{"foo": {"bar": 10}},
|
210 |
+
id="merge_empty_dict",
|
211 |
+
),
|
212 |
+
pytest.param(
|
213 |
+
"foo",
|
214 |
+
{"foo": {"bar": 10}},
|
215 |
+
{"xyz": 10},
|
216 |
+
{"foo": {"bar": 10}, "xyz": 10},
|
217 |
+
id="merge_different_node",
|
218 |
+
),
|
219 |
+
],
|
220 |
+
)
|
221 |
+
def test_merge_with_readonly_nop(
|
222 |
+
readonly_key: str,
|
223 |
+
cfg1: Dict[str, Any],
|
224 |
+
cfg2: Dict[str, Any],
|
225 |
+
expected: Dict[str, Any],
|
226 |
+
) -> None:
|
227 |
+
c = OmegaConf.create(cfg1)
|
228 |
+
OmegaConf.set_readonly(OmegaConf.select(c, readonly_key), True)
|
229 |
+
c.merge_with(cfg2)
|
230 |
+
assert c == OmegaConf.create(expected)
|
tests/test_select.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from typing import Any, Optional
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
from pytest import raises
|
6 |
+
|
7 |
+
from omegaconf import MissingMandatoryValue, OmegaConf
|
8 |
+
|
9 |
+
from . import does_not_raise
|
10 |
+
|
11 |
+
|
12 |
+
@pytest.mark.parametrize("struct", [True, False, None]) # type: ignore
|
13 |
+
def test_select_key_from_empty(struct: Optional[bool]) -> None:
|
14 |
+
c = OmegaConf.create()
|
15 |
+
OmegaConf.set_struct(c, struct)
|
16 |
+
assert OmegaConf.select(c, "not_there") is None
|
17 |
+
|
18 |
+
|
19 |
+
@pytest.mark.parametrize( # type: ignore
|
20 |
+
"cfg, keys, expected, expectation",
|
21 |
+
[
|
22 |
+
({}, "nope", None, does_not_raise()),
|
23 |
+
({}, "not.there", None, does_not_raise()),
|
24 |
+
({}, "still.not.there", None, does_not_raise()),
|
25 |
+
({"c": 1}, "c", 1, does_not_raise()),
|
26 |
+
({"a": {"v": 1}}, "a", {"v": 1}, does_not_raise()),
|
27 |
+
({"a": {"v": 1}}, "a.v", 1, does_not_raise()),
|
28 |
+
({"missing": "???"}, "missing", None, does_not_raise()),
|
29 |
+
([], "0", None, does_not_raise()),
|
30 |
+
([1, "2"], ("0", "1"), (1, "2"), does_not_raise()),
|
31 |
+
(
|
32 |
+
[1, {"a": 10, "c": ["foo", "bar"]}],
|
33 |
+
("0", "1.a", "1.b", "1.c.0", "1.c.1"),
|
34 |
+
(1, 10, None, "foo", "bar"),
|
35 |
+
does_not_raise(),
|
36 |
+
),
|
37 |
+
([1, 2, 3], "a", None, raises(TypeError)),
|
38 |
+
(
|
39 |
+
{"a": {"v": 1}, "b": {"v": 1}},
|
40 |
+
"",
|
41 |
+
{"a": {"v": 1}, "b": {"v": 1}},
|
42 |
+
does_not_raise(),
|
43 |
+
),
|
44 |
+
(
|
45 |
+
{"dict": {"one": 1}, "foo": "one=${dict.one}"},
|
46 |
+
"foo",
|
47 |
+
"one=1",
|
48 |
+
does_not_raise(),
|
49 |
+
),
|
50 |
+
(
|
51 |
+
{"dict": {"foo": "one=${one}"}, "one": 1},
|
52 |
+
"dict.foo",
|
53 |
+
"one=1",
|
54 |
+
does_not_raise(),
|
55 |
+
),
|
56 |
+
({"dict": {"foo": "one=${foo:1}"}}, "dict.foo", "one=_1_", does_not_raise()),
|
57 |
+
],
|
58 |
+
)
|
59 |
+
def test_select(
|
60 |
+
restore_resolvers: Any, cfg: Any, keys: Any, expected: Any, expectation: Any
|
61 |
+
) -> None:
|
62 |
+
if not isinstance(keys, (tuple, list)):
|
63 |
+
keys = [keys]
|
64 |
+
if not isinstance(expected, (tuple, list)):
|
65 |
+
expected = [expected]
|
66 |
+
OmegaConf.register_resolver("foo", lambda x: f"_{x}_")
|
67 |
+
|
68 |
+
c = OmegaConf.create(cfg)
|
69 |
+
with expectation:
|
70 |
+
for idx, key in enumerate(keys):
|
71 |
+
assert OmegaConf.select(c, key) == expected[idx]
|
72 |
+
|
73 |
+
|
74 |
+
def test_select_from_dict() -> None:
|
75 |
+
c = OmegaConf.create({"missing": "???"})
|
76 |
+
with pytest.raises(MissingMandatoryValue):
|
77 |
+
OmegaConf.select(c, "missing", throw_on_missing=True)
|
78 |
+
assert OmegaConf.select(c, "missing", throw_on_missing=False) is None
|
79 |
+
assert OmegaConf.select(c, "missing") is None
|
80 |
+
|
81 |
+
|
82 |
+
def test_select_deprecated() -> None:
|
83 |
+
c = OmegaConf.create({"foo": "bar"})
|
84 |
+
with pytest.warns(
|
85 |
+
expected_warning=UserWarning,
|
86 |
+
match=re.escape("select() is deprecated, use OmegaConf.select(). (Since 2.0)"),
|
87 |
+
):
|
88 |
+
c.select("foo")
|
tests/test_serialization.py
ADDED
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
import io
|
3 |
+
import os
|
4 |
+
import pathlib
|
5 |
+
import pickle
|
6 |
+
import tempfile
|
7 |
+
from pathlib import Path
|
8 |
+
from textwrap import dedent
|
9 |
+
from typing import Any, Dict, Type
|
10 |
+
|
11 |
+
import pytest
|
12 |
+
|
13 |
+
from omegaconf import MISSING, DictConfig, OmegaConf
|
14 |
+
|
15 |
+
from . import PersonA, PersonD
|
16 |
+
|
17 |
+
|
18 |
+
def save_load_from_file(conf: Any, resolve: bool, expected: Any) -> None:
|
19 |
+
if expected is None:
|
20 |
+
expected = conf
|
21 |
+
try:
|
22 |
+
with tempfile.NamedTemporaryFile(
|
23 |
+
mode="wt", delete=False, encoding="utf-8"
|
24 |
+
) as fp:
|
25 |
+
OmegaConf.save(conf, fp.file, resolve=resolve) # type: ignore
|
26 |
+
with io.open(os.path.abspath(fp.name), "rt", encoding="utf-8") as handle:
|
27 |
+
c2 = OmegaConf.load(handle)
|
28 |
+
assert c2 == expected
|
29 |
+
finally:
|
30 |
+
os.unlink(fp.name)
|
31 |
+
|
32 |
+
|
33 |
+
def save_load_from_filename(
|
34 |
+
conf: Any, resolve: bool, expected: Any, file_class: Type[Any]
|
35 |
+
) -> None:
|
36 |
+
if expected is None:
|
37 |
+
expected = conf
|
38 |
+
# note that delete=False here is a work around windows incompetence.
|
39 |
+
try:
|
40 |
+
with tempfile.NamedTemporaryFile(delete=False) as fp:
|
41 |
+
filepath = file_class(fp.name)
|
42 |
+
OmegaConf.save(conf, filepath, resolve=resolve)
|
43 |
+
c2 = OmegaConf.load(filepath)
|
44 |
+
assert c2 == expected
|
45 |
+
finally:
|
46 |
+
os.unlink(fp.name)
|
47 |
+
|
48 |
+
|
49 |
+
def test_load_from_invalid() -> None:
|
50 |
+
with pytest.raises(TypeError):
|
51 |
+
OmegaConf.load(3.1415) # type: ignore
|
52 |
+
|
53 |
+
|
54 |
+
@pytest.mark.parametrize(
|
55 |
+
"input_,resolve,expected,file_class",
|
56 |
+
[
|
57 |
+
({"a": 10}, False, None, str),
|
58 |
+
({"foo": 10, "bar": "${foo}"}, False, None, str),
|
59 |
+
({"foo": 10, "bar": "${foo}"}, False, None, pathlib.Path),
|
60 |
+
({"foo": 10, "bar": "${foo}"}, False, {"foo": 10, "bar": 10}, str),
|
61 |
+
([u"שלום"], False, None, str),
|
62 |
+
],
|
63 |
+
)
|
64 |
+
class TestSaveLoad:
|
65 |
+
def test_save_load__from_file(
|
66 |
+
self,
|
67 |
+
input_: Dict[str, Any],
|
68 |
+
resolve: bool,
|
69 |
+
expected: Any,
|
70 |
+
file_class: Type[Any],
|
71 |
+
) -> None:
|
72 |
+
cfg = OmegaConf.create(input_)
|
73 |
+
save_load_from_file(cfg, resolve, expected)
|
74 |
+
|
75 |
+
def test_save_load__from_filename(
|
76 |
+
self,
|
77 |
+
input_: Dict[str, Any],
|
78 |
+
resolve: bool,
|
79 |
+
expected: Any,
|
80 |
+
file_class: Type[Any],
|
81 |
+
) -> None:
|
82 |
+
cfg = OmegaConf.create(input_)
|
83 |
+
save_load_from_filename(cfg, resolve, expected, file_class)
|
84 |
+
|
85 |
+
|
86 |
+
@pytest.mark.parametrize(
|
87 |
+
"input_,resolve,expected,file_class",
|
88 |
+
[
|
89 |
+
(PersonA, False, {"age": 18, "registered": True}, str),
|
90 |
+
(PersonD, False, {"age": 18, "registered": True}, str),
|
91 |
+
(PersonA(), False, {"age": 18, "registered": True}, str),
|
92 |
+
(PersonD(), False, {"age": 18, "registered": True}, str),
|
93 |
+
],
|
94 |
+
)
|
95 |
+
class TestSaveLoadStructured:
|
96 |
+
def test_save_load__from_file(
|
97 |
+
self,
|
98 |
+
input_: Dict[str, Any],
|
99 |
+
resolve: bool,
|
100 |
+
expected: Any,
|
101 |
+
file_class: Type[Any],
|
102 |
+
) -> None:
|
103 |
+
save_load_from_file(input_, resolve, expected)
|
104 |
+
|
105 |
+
def test_save_load__from_filename(
|
106 |
+
self,
|
107 |
+
input_: Dict[str, Any],
|
108 |
+
resolve: bool,
|
109 |
+
expected: Any,
|
110 |
+
file_class: Type[Any],
|
111 |
+
) -> None:
|
112 |
+
save_load_from_filename(input_, resolve, expected, file_class)
|
113 |
+
|
114 |
+
|
115 |
+
def test_save_illegal_type() -> None:
|
116 |
+
with pytest.raises(TypeError):
|
117 |
+
OmegaConf.save(OmegaConf.create(), 1000) # type: ignore
|
118 |
+
|
119 |
+
|
120 |
+
def test_pickle_dict() -> None:
|
121 |
+
with tempfile.TemporaryFile() as fp:
|
122 |
+
c = OmegaConf.create({"a": "b"})
|
123 |
+
pickle.dump(c, fp)
|
124 |
+
fp.flush()
|
125 |
+
fp.seek(0)
|
126 |
+
c1 = pickle.load(fp)
|
127 |
+
assert c == c1
|
128 |
+
|
129 |
+
|
130 |
+
def test_pickle_list() -> None:
|
131 |
+
with tempfile.TemporaryFile() as fp:
|
132 |
+
c = OmegaConf.create([1, 2, 3])
|
133 |
+
pickle.dump(c, fp)
|
134 |
+
fp.flush()
|
135 |
+
fp.seek(0)
|
136 |
+
c1 = pickle.load(fp)
|
137 |
+
assert c == c1
|
138 |
+
|
139 |
+
|
140 |
+
def test_load_duplicate_keys_top() -> None:
|
141 |
+
from yaml.constructor import ConstructorError
|
142 |
+
|
143 |
+
try:
|
144 |
+
with tempfile.NamedTemporaryFile(delete=False) as fp:
|
145 |
+
content = dedent(
|
146 |
+
"""\
|
147 |
+
a:
|
148 |
+
b: 1
|
149 |
+
a:
|
150 |
+
b: 2
|
151 |
+
"""
|
152 |
+
)
|
153 |
+
fp.write(content.encode("utf-8"))
|
154 |
+
with pytest.raises(ConstructorError):
|
155 |
+
OmegaConf.load(fp.name)
|
156 |
+
finally:
|
157 |
+
os.unlink(fp.name)
|
158 |
+
|
159 |
+
|
160 |
+
def test_load_duplicate_keys_sub() -> None:
|
161 |
+
from yaml.constructor import ConstructorError
|
162 |
+
|
163 |
+
try:
|
164 |
+
with tempfile.NamedTemporaryFile(delete=False) as fp:
|
165 |
+
content = dedent(
|
166 |
+
"""\
|
167 |
+
a:
|
168 |
+
b: 1
|
169 |
+
c: 2
|
170 |
+
b: 3
|
171 |
+
"""
|
172 |
+
)
|
173 |
+
fp.write(content.encode("utf-8"))
|
174 |
+
with pytest.raises(ConstructorError):
|
175 |
+
OmegaConf.load(fp.name)
|
176 |
+
finally:
|
177 |
+
os.unlink(fp.name)
|
178 |
+
|
179 |
+
|
180 |
+
def test_load_empty_file(tmpdir: str) -> None:
|
181 |
+
empty = Path(tmpdir) / "test.yaml"
|
182 |
+
empty.touch()
|
183 |
+
|
184 |
+
assert OmegaConf.load(empty) == {}
|
185 |
+
|
186 |
+
|
187 |
+
def test_pickle_missing() -> None:
|
188 |
+
cfg = DictConfig(content=MISSING)
|
189 |
+
with tempfile.TemporaryFile() as fp:
|
190 |
+
import pickle
|
191 |
+
|
192 |
+
pickle.dump(cfg, fp)
|
193 |
+
fp.flush()
|
194 |
+
fp.seek(0)
|
195 |
+
cfg2 = pickle.load(fp)
|
196 |
+
assert cfg == cfg2
|
197 |
+
|
198 |
+
|
199 |
+
def test_pickle_none() -> None:
|
200 |
+
cfg = DictConfig(content=None)
|
201 |
+
with tempfile.TemporaryFile() as fp:
|
202 |
+
import pickle
|
203 |
+
|
204 |
+
pickle.dump(cfg, fp)
|
205 |
+
fp.flush()
|
206 |
+
fp.seek(0)
|
207 |
+
cfg2 = pickle.load(fp)
|
208 |
+
assert cfg == cfg2
|
tests/test_struct.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from typing import Any, Dict
|
3 |
+
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from omegaconf import OmegaConf
|
7 |
+
from omegaconf.errors import ConfigKeyError
|
8 |
+
|
9 |
+
|
10 |
+
def test_struct_default() -> None:
|
11 |
+
c = OmegaConf.create()
|
12 |
+
assert c.not_found is None
|
13 |
+
assert OmegaConf.is_struct(c) is None
|
14 |
+
|
15 |
+
|
16 |
+
def test_struct_set_on_dict() -> None:
|
17 |
+
c = OmegaConf.create({"a": {}})
|
18 |
+
OmegaConf.set_struct(c, True)
|
19 |
+
# Throwing when it hits foo, so exception key is a.foo and not a.foo.bar
|
20 |
+
with pytest.raises(AttributeError, match=re.escape("a.foo")):
|
21 |
+
# noinspection PyStatementEffect
|
22 |
+
c.a.foo.bar
|
23 |
+
|
24 |
+
|
25 |
+
def test_struct_set_on_nested_dict() -> None:
|
26 |
+
c = OmegaConf.create(dict(a=dict(b=10)))
|
27 |
+
OmegaConf.set_struct(c, True)
|
28 |
+
with pytest.raises(AttributeError):
|
29 |
+
# noinspection PyStatementEffect
|
30 |
+
c.foo
|
31 |
+
|
32 |
+
assert "a" in c
|
33 |
+
assert c.a.b == 10
|
34 |
+
with pytest.raises(AttributeError, match=re.escape("a.foo")):
|
35 |
+
# noinspection PyStatementEffect
|
36 |
+
c.a.foo
|
37 |
+
|
38 |
+
|
39 |
+
def test_merge_dotlist_into_struct() -> None:
|
40 |
+
c = OmegaConf.create(dict(a=dict(b=10)))
|
41 |
+
OmegaConf.set_struct(c, True)
|
42 |
+
with pytest.raises(AttributeError, match=re.escape("foo")):
|
43 |
+
c.merge_with_dotlist(["foo=1"])
|
44 |
+
|
45 |
+
|
46 |
+
@pytest.mark.parametrize("in_base, in_merged", [(dict(), dict(a=10))]) # type: ignore
|
47 |
+
def test_merge_config_with_struct(
|
48 |
+
in_base: Dict[str, Any], in_merged: Dict[str, Any]
|
49 |
+
) -> None:
|
50 |
+
base = OmegaConf.create(in_base)
|
51 |
+
merged = OmegaConf.create(in_merged)
|
52 |
+
OmegaConf.set_struct(base, True)
|
53 |
+
with pytest.raises(ConfigKeyError):
|
54 |
+
OmegaConf.merge(base, merged)
|
55 |
+
|
56 |
+
|
57 |
+
def test_struct_contain_missing() -> None:
|
58 |
+
c = OmegaConf.create(dict())
|
59 |
+
OmegaConf.set_struct(c, True)
|
60 |
+
assert "foo" not in c
|