Skip to content

Commit 49a2574

Browse files
authored
strip_meta is deprecated and will be removed in v5.0.0 (#795)
1 parent b967620 commit 49a2574

File tree

11 files changed

+64
-43
lines changed

11 files changed

+64
-43
lines changed

CHANGELOG.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ Deprecated
4141
- ``Path.__call__`` is deprecated and will be removed in v5.0.0. Use the
4242
``absolute`` or ``relative`` properties instead (`#794
4343
<https://github.com/omni-us/jsonargparse/pull/794>`__).
44+
- ``strip_meta`` is deprecated and will be removed in v5.0.0. Instead use
45+
``.clone(with_meta=False)`` (`#795
46+
<https://github.com/omni-us/jsonargparse/pull/795>`__).
4447

4548

4649
v4.42.0 (2025-10-14)

jsonargparse/_core.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,10 @@
7171
is_meta_key,
7272
patch_namespace,
7373
recreate_branches,
74+
remove_meta,
7475
split_key,
7576
split_key_leaf,
7677
split_key_root,
77-
strip_meta,
7878
)
7979
from ._optionals import (
8080
_get_config_read_mode,
@@ -393,7 +393,7 @@ def _parse_common(
393393
self.validate(cfg, skip_required=skip_required)
394394

395395
if not (with_meta or (with_meta is None and self._default_meta)):
396-
cfg = strip_meta(cfg)
396+
cfg = cfg.clone(with_meta=False)
397397

398398
return cfg
399399

@@ -793,7 +793,7 @@ def dump(
793793
skip_validation = deprecated_skip_check(ArgumentParser.dump, kwargs, skip_validation)
794794
check_valid_dump_format(format)
795795

796-
cfg = strip_meta(cfg)
796+
cfg = cfg.clone(with_meta=False)
797797

798798
with parser_context(load_value_mode=self.parser_mode):
799799
if not skip_validation:
@@ -926,7 +926,7 @@ def check_overwrite(path):
926926

927927
if not skip_validation:
928928
with parser_context(load_value_mode=self.parser_mode):
929-
self.validate(strip_meta(cfg), branch=branch)
929+
self.validate(cfg.clone(with_meta=False), branch=branch)
930930

931931
ActionLink.strip_link_target_keys(self, cfg)
932932

@@ -937,7 +937,7 @@ def is_path_action(key):
937937
def save_path(val):
938938
val_path = Path(os.path.basename(val["__path__"].absolute), mode="fc")
939939
check_overwrite(val_path)
940-
val_out = strip_meta(val)
940+
val_out = remove_meta(val)
941941
if isinstance(val, Namespace):
942942
val_out = val_out.as_dict()
943943
if "__orig__" in val:
@@ -1258,7 +1258,7 @@ def instantiate_classes(
12581258
order = ActionLink.instantiation_order(self)
12591259
components = ActionLink.reorder(order, components)
12601260

1261-
cfg = strip_meta(cfg)
1261+
cfg = cfg.clone(with_meta=False)
12621262
for component in components:
12631263
ActionLink.apply_instantiation_links(self, cfg, target=component.dest)
12641264
if isinstance(component, ActionTypeHint):

jsonargparse/_deprecated.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from importlib import import_module
1010
from pathlib import Path
1111
from types import ModuleType
12-
from typing import Any, Callable, Dict, Optional, Set
12+
from typing import Any, Callable, Dict, Optional, Set, overload
1313

1414
from ._common import Action, null_logger
1515
from ._common import LoggerProperty as InternalLoggerProperty
@@ -32,6 +32,7 @@
3232
"set_docstring_parse_options",
3333
"set_config_read_mode",
3434
"set_url_support",
35+
"strip_meta",
3536
"usage_and_exit_error_handler",
3637
]
3738

@@ -705,6 +706,27 @@ def namespace_to_dict(namespace: Namespace) -> Dict[str, Any]:
705706
return namespace.clone().as_dict()
706707

707708

709+
@overload
710+
def strip_meta(cfg: "Namespace") -> "Namespace": ... # pragma: no cover
711+
712+
713+
@overload
714+
def strip_meta(cfg: Dict[str, Any]) -> Dict[str, Any]: ... # pragma: no cover
715+
716+
717+
@deprecated(
718+
"""
719+
strip_meta was deprecated in v4.43.0 and will be removed in v5.0.0.
720+
Instead use ``.clone(with_meta=False)``.
721+
"""
722+
)
723+
def strip_meta(cfg):
724+
"""Removes all metadata keys from a configuration object."""
725+
from ._namespace import remove_meta
726+
727+
return remove_meta(cfg)
728+
729+
708730
class HelpFormatterDeprecations:
709731
"""Helper class for DefaultHelpFormatter deprecations. Will be removed in v5.0.0."""
710732

jsonargparse/_jsonschema.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from ._actions import _is_action_value_list
77
from ._common import Action, parser_context
88
from ._loaders_dumpers import get_loader_exceptions, load_value
9-
from ._namespace import strip_meta
9+
from ._namespace import remove_meta
1010
from ._optionals import (
1111
get_jsonschema_exceptions,
1212
import_jsonschema,
@@ -73,7 +73,7 @@ def __call__(self, *args, **kwargs):
7373
return class_type(**kwargs)
7474
val = self._check_type(args[2])
7575
if not self._with_meta:
76-
val = strip_meta(val)
76+
val = remove_meta(val)
7777
setattr(args[1], self.dest, val)
7878
return None
7979

jsonargparse/_namespace.py

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,11 @@
1313
Set,
1414
Tuple,
1515
Union,
16-
overload,
1716
)
1817

1918
__all__ = [
2019
"Namespace",
2120
"dict_to_namespace",
22-
"strip_meta",
2321
]
2422

2523

@@ -48,23 +46,7 @@ def is_meta_key(key: str) -> bool:
4846
return leaf_key in meta_keys
4947

5048

51-
@overload
52-
def strip_meta(cfg: "Namespace") -> "Namespace": ... # pragma: no cover
53-
54-
55-
@overload
56-
def strip_meta(cfg: Dict[str, Any]) -> Dict[str, Any]: ... # pragma: no cover
57-
58-
59-
def strip_meta(cfg):
60-
"""Removes all metadata keys from a configuration object.
61-
62-
Args:
63-
cfg: The configuration object to strip.
64-
65-
Returns:
66-
A copy of the configuration object excluding all metadata keys.
67-
"""
49+
def remove_meta(cfg: Union["Namespace", dict]):
6850
if cfg:
6951
cfg = recreate_branches(cfg, skip_keys=meta_keys)
7052
return cfg
@@ -275,9 +257,13 @@ def get_sorted_keys(self, branches: bool = True, key_filter: Callable = is_meta_
275257
keys.sort(key=lambda x: -len(split_key(x)))
276258
return keys
277259

278-
def clone(self) -> "Namespace":
279-
"""Creates an new identical nested namespace."""
280-
return recreate_branches(self)
260+
def clone(self, with_meta: bool = True) -> "Namespace":
261+
"""Creates an new copy of the nested namespace.
262+
263+
Args:
264+
with_meta: Whether to include metadata keys in the copy.
265+
"""
266+
return recreate_branches(self, skip_keys=None if with_meta else meta_keys)
281267

282268
def update(
283269
self, value: Union["Namespace", Any], key: Optional[str] = None, only_unset: bool = False

jsonargparse_tests/test_actions.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
ArgumentError,
1313
ArgumentParser,
1414
Namespace,
15-
strip_meta,
1615
)
1716
from jsonargparse_tests.conftest import get_parser_help, json_or_yaml_dump
1817

@@ -238,7 +237,7 @@ def test_action_parser_parse_path(composed_parsers):
238237
cfg = parser.parse_path(yaml_main)
239238
assert "inner2.yaml" == str(cfg.inner2.__path__)
240239
assert "inner3.yaml" == str(cfg.inner2.inner3.__path__)
241-
assert expected == strip_meta(cfg).as_dict()
240+
assert expected == cfg.clone(with_meta=False).as_dict()
242241

243242
yaml_main2 = yaml_main.parent / "main2.yaml"
244243
yaml_main2.write_text(parser.dump(cfg))

jsonargparse_tests/test_core.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
ArgumentParser,
2424
Namespace,
2525
set_parsing_settings,
26-
strip_meta,
2726
)
2827
from jsonargparse._formatters import get_env_var
2928
from jsonargparse._namespace import NSKeyError
@@ -667,7 +666,7 @@ def rm_out_files():
667666

668667
with subtests.test("parse_path with metadata"):
669668
cfg1 = parser.parse_path(main_file_in, with_meta=True)
670-
assert expected == strip_meta(cfg1)
669+
assert expected == cfg1.clone(with_meta=False)
671670
assert str(cfg1.subparser["__path__"]) == "subparser.yaml"
672671
if jsonschema_support:
673672
assert str(cfg1.schema["__path__"]) == "schema.json"

jsonargparse_tests/test_deprecated.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
deprecation_warning,
3535
namespace_to_dict,
3636
shown_deprecation_warnings,
37+
strip_meta,
3738
usage_and_exit_error_handler,
3839
)
3940
from jsonargparse._formatters import DefaultHelpFormatter
@@ -757,6 +758,20 @@ def test_namespace_to_dict():
757758
)
758759

759760

761+
def test_strip_meta():
762+
ns = Namespace(x=1, __path__="path")
763+
with catch_warnings(record=True) as w:
764+
result = strip_meta(ns)
765+
assert result == Namespace(x=1)
766+
assert_deprecation_warn(
767+
w,
768+
message="strip_meta was deprecated",
769+
code="result = strip_meta(ns)",
770+
)
771+
result = strip_meta(ns.as_dict())
772+
assert result == {"x": 1}
773+
774+
760775
@pytest.mark.skipif(not ruamel_support, reason="ruamel.yaml package is required")
761776
def test_DefaultHelpFormatter_yaml_comments(parser):
762777
parser.add_argument("--arg", type=int, help="Description")

jsonargparse_tests/test_jsonnet.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
ActionJsonSchema,
1212
ArgumentError,
1313
ArgumentParser,
14-
strip_meta,
1514
)
1615
from jsonargparse._optionals import jsonnet_support, pyyaml_available
1716
from jsonargparse_tests.conftest import (
@@ -188,19 +187,19 @@ def test_action_jsonnet_save_config_metadata(parser, tmp_path):
188187
# parse using saved config and verify result is the same
189188
cfg2 = parser.parse_args([f"--cfg={output_config}"])
190189
cfg2.cfg = None
191-
assert strip_meta(cfg) == strip_meta(cfg2)
190+
assert cfg.clone(with_meta=False) == cfg2.clone(with_meta=False)
192191

193192
# save the config without metadata and verify it is saved as a single file
194193
output_config.unlink()
195194
output_jsonnet.unlink()
196-
parser.save(strip_meta(cfg), output_config)
195+
parser.save(cfg.clone(with_meta=False), output_config)
197196
assert output_config.is_file()
198197
assert not output_jsonnet.is_file()
199198

200199
# parse using saved config and verify result is the same
201200
cfg3 = parser.parse_args([f"--cfg={output_config}"])
202201
cfg3.cfg = None
203-
assert strip_meta(cfg) == strip_meta(cfg3)
202+
assert cfg.clone(with_meta=False) == cfg3.clone(with_meta=False)
204203

205204

206205
@skip_if_jsonschema_unavailable

jsonargparse_tests/test_signatures.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
ArgumentError,
1414
Namespace,
1515
lazy_instance,
16-
strip_meta,
1716
)
1817
from jsonargparse._actions import _find_action
1918
from jsonargparse._optionals import docstring_parser_support
@@ -685,7 +684,7 @@ def test_add_function_group_config_within_config(parser, tmp_cwd):
685684

686685
cfg = parser.parse_args([f"--cfg={cfg_path}"])
687686
assert str(cfg.func.__path__) == str(subcfg_path)
688-
assert strip_meta(cfg.func) == Namespace(a1="one", a2=2.0, a3=True, a4=None)
687+
assert cfg.func.clone(with_meta=False) == Namespace(a1="one", a2=2.0, a3=True, a4=None)
689688

690689

691690
def func_param_conflict(p1: int, cfg: dict):

0 commit comments

Comments
 (0)