Skip to content

Commit 76fabbe

Browse files
authored
Deprecate ArgumentParser.default_meta property and with_meta parameter of ArgumentParser.parse_* (#810)
1 parent 3347996 commit 76fabbe

File tree

9 files changed

+128
-93
lines changed

9 files changed

+128
-93
lines changed

CHANGELOG.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@ Changed
2222
for the corresponding parser/subcommand (`#809
2323
<https://github.com/omni-us/jsonargparse/pull/809>`__).
2424

25+
Deprecated
26+
^^^^^^^^^^
27+
- ``ArgumentParser.default_meta`` property and ``with_meta`` parameter of
28+
``ArgumentParser.parse_*`` are deprecated and will be removed in v5.0.0.
29+
Instead use ``.clone(with_meta=...)`` (`#810
30+
<https://github.com/omni-us/jsonargparse/pull/810>`__).
31+
2532

2633
v4.43.0 (2025-11-11)
2734
--------------------

jsonargparse/_cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def auto_cli(
9191
if unexpected:
9292
raise ValueError(f"Unexpected components, not class or function: {unexpected}")
9393

94-
parser = parser_class(default_meta=False, **kwargs)
94+
parser = parser_class(**kwargs)
9595
parser.add_argument("--config", action=ActionConfigFile, help=config_help)
9696

9797
if not isinstance(components, (list, dict)):

jsonargparse/_core.py

Lines changed: 5 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,6 @@ def __init__(
242242
dump_header: Optional[list[str]] = None,
243243
default_config_files: Optional[list[Union[str, os.PathLike]]] = None,
244244
default_env: bool = False,
245-
default_meta: bool = True,
246245
**kwargs,
247246
) -> None:
248247
"""Initializer for ArgumentParser instance.
@@ -261,7 +260,6 @@ def __init__(
261260
dump_header: Header to include as comment when dumping a config object.
262261
default_config_files: Default config file locations, e.g. ``['~/.config/myapp/*.yaml']``.
263262
default_env: Set the default value on whether to parse environment variables.
264-
default_meta: Set the default value on whether to include metadata in config objects.
265263
"""
266264
super().__init__(*args, formatter_class=formatter_class, logger=logger, **kwargs)
267265
self._group_class = get_argument_group_class(self)
@@ -271,7 +269,6 @@ def __init__(
271269
self.required_args: set[str] = set()
272270
self.save_path_content: set[str] = set()
273271
self.default_config_files = default_config_files
274-
self.default_meta = default_meta
275272
self.default_env = default_env
276273
self.env_prefix = env_prefix
277274
self.parser_mode = parser_mode
@@ -340,7 +337,6 @@ def _parse_common(
340337
cfg: Namespace,
341338
env: Optional[bool],
342339
defaults: bool,
343-
with_meta: Optional[bool],
344340
skip_validation: bool,
345341
skip_required: bool = False,
346342
skip_subcommands: bool = False,
@@ -352,7 +348,6 @@ def _parse_common(
352348
cfg: The configuration object.
353349
env: Whether to merge with the parsed environment, None to use parser's default.
354350
defaults: Whether to merge with the parser's defaults.
355-
with_meta: Whether to include metadata in config object, None to use parser's default.
356351
skip_validation: Whether to skip validation of configuration.
357352
skip_required: Whether to skip check of required arguments.
358353
skip_subcommands: Whether to skip subcommand processing.
@@ -387,9 +382,6 @@ def _parse_common(
387382
if not skip_validation:
388383
self.validate(cfg, skip_required=skip_required)
389384

390-
if not (with_meta or (with_meta is None and self._default_meta)):
391-
cfg = cfg.clone(with_meta=False)
392-
393385
return cfg
394386

395387
def _parse_defaults_and_environ(
@@ -417,7 +409,6 @@ def parse_args( # type: ignore[override]
417409
namespace: Optional[Namespace] = None,
418410
env: Optional[bool] = None,
419411
defaults: bool = True,
420-
with_meta: Optional[bool] = None,
421412
**kwargs,
422413
) -> Namespace:
423414
"""Parses command line argument strings.
@@ -430,7 +421,6 @@ def parse_args( # type: ignore[override]
430421
args: List of arguments to parse or None to use sys.argv.
431422
env: Whether to merge with the parsed environment, None to use parser's default.
432423
defaults: Whether to merge with the parser's defaults.
433-
with_meta: Whether to include metadata in config object, None to use parser's default.
434424
435425
Returns:
436426
A config object with all parsed values.
@@ -465,7 +455,6 @@ def parse_args( # type: ignore[override]
465455
cfg=cfg,
466456
env=env,
467457
defaults=defaults,
468-
with_meta=with_meta,
469458
skip_validation=skip_validation,
470459
)
471460

@@ -481,7 +470,6 @@ def parse_object(
481470
cfg_base: Optional[Namespace] = None,
482471
env: Optional[bool] = None,
483472
defaults: bool = True,
484-
with_meta: Optional[bool] = None,
485473
**kwargs,
486474
) -> Namespace:
487475
"""Parses configuration given as an object.
@@ -490,7 +478,6 @@ def parse_object(
490478
cfg_obj: The configuration object.
491479
env: Whether to merge with the parsed environment, None to use parser's default.
492480
defaults: Whether to merge with the parser's defaults.
493-
with_meta: Whether to include metadata in config object, None to use parser's default.
494481
495482
Returns:
496483
A config object with all parsed values.
@@ -513,7 +500,6 @@ def parse_object(
513500
cfg=cfg,
514501
env=env,
515502
defaults=defaults,
516-
with_meta=with_meta,
517503
skip_validation=skip_validation,
518504
skip_required=skip_required,
519505
)
@@ -558,15 +544,13 @@ def parse_env(
558544
self,
559545
env: Optional[dict[str, str]] = None,
560546
defaults: bool = True,
561-
with_meta: Optional[bool] = None,
562547
**kwargs,
563548
) -> Namespace:
564549
"""Parses environment variables.
565550
566551
Args:
567552
env: The environment object to use, if None `os.environ` is used.
568553
defaults: Whether to merge with the parser's defaults.
569-
with_meta: Whether to include metadata in config object, None to use parser's default.
570554
571555
Returns:
572556
A config object with all parsed values.
@@ -582,7 +566,6 @@ def parse_env(
582566
kwargs = {
583567
"env": True,
584568
"defaults": defaults,
585-
"with_meta": with_meta,
586569
"skip_validation": skip_validation,
587570
"skip_subcommands": skip_subcommands,
588571
}
@@ -603,7 +586,6 @@ def parse_path(
603586
ext_vars: Optional[dict] = None,
604587
env: Optional[bool] = None,
605588
defaults: bool = True,
606-
with_meta: Optional[bool] = None,
607589
**kwargs,
608590
) -> Namespace:
609591
"""Parses a configuration file given its path.
@@ -613,7 +595,6 @@ def parse_path(
613595
ext_vars: Optional external variables used for parsing jsonnet.
614596
env: Whether to merge with the parsed environment, None to use parser's default.
615597
defaults: Whether to merge with the parser's defaults.
616-
with_meta: Whether to include metadata in config object, None to use parser's default.
617598
618599
Returns:
619600
A config object with all parsed values.
@@ -625,12 +606,11 @@ def parse_path(
625606
with change_to_path_dir(fpath):
626607
cfg_str = fpath.get_content()
627608
parsed_cfg = self.parse_string(
628-
cfg_str,
629-
os.path.basename(cfg_path),
630-
ext_vars,
631-
env,
632-
defaults,
633-
with_meta,
609+
cfg_str=cfg_str,
610+
cfg_path=os.path.basename(cfg_path),
611+
ext_vars=ext_vars,
612+
env=env,
613+
defaults=defaults,
634614
**kwargs,
635615
)
636616

@@ -644,7 +624,6 @@ def parse_string(
644624
ext_vars: Optional[dict] = None,
645625
env: Optional[bool] = None,
646626
defaults: bool = True,
647-
with_meta: Optional[bool] = None,
648627
**kwargs,
649628
) -> Namespace:
650629
"""Parses configuration given as a string.
@@ -655,7 +634,6 @@ def parse_string(
655634
ext_vars: Optional external variables used for parsing jsonnet.
656635
env: Whether to merge with the parsed environment, None to use parser's default.
657636
defaults: Whether to merge with the parser's defaults.
658-
with_meta: Whether to include metadata in config object, None to use parser's default.
659637
660638
Returns:
661639
A config object with all parsed values.
@@ -679,7 +657,6 @@ def parse_string(
679657
cfg=cfg,
680658
env=env,
681659
defaults=defaults,
682-
with_meta=with_meta,
683660
skip_validation=skip_validation,
684661
fail_no_subcommand=fail_no_subcommand,
685662
)
@@ -1051,7 +1028,6 @@ def get_defaults(self, skip_validation: bool = False, **kwargs) -> Namespace:
10511028
cfg=cfg,
10521029
env=False,
10531030
defaults=False,
1054-
with_meta=None,
10551031
skip_validation=skip_validation,
10561032
skip_required=True,
10571033
)
@@ -1555,25 +1531,6 @@ def default_env(self, default_env: bool):
15551531
for subparser in self._subcommands_action._name_parser_map.values():
15561532
subparser.default_env = self._default_env
15571533

1558-
@property
1559-
def default_meta(self) -> bool:
1560-
"""Whether by default metadata is included in config objects.
1561-
1562-
:getter: Returns the current default metadata setting.
1563-
:setter: Sets the default metadata setting.
1564-
1565-
Raises:
1566-
ValueError: If an invalid value is given.
1567-
"""
1568-
return self._default_meta
1569-
1570-
@default_meta.setter
1571-
def default_meta(self, default_meta: bool):
1572-
if isinstance(default_meta, bool):
1573-
self._default_meta = default_meta
1574-
else:
1575-
raise ValueError("default_meta expects a boolean.")
1576-
15771534
@property
15781535
def env_prefix(self) -> Union[bool, str]:
15791536
"""The environment variables prefix property.

jsonargparse/_deprecated.py

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,19 +107,24 @@ def parse_as_dict_patch():
107107

108108
assert not hasattr(ArgumentParser, "_unpatched_init")
109109

110-
message = """
110+
message_parse_as_dict = """
111111
``parse_as_dict`` parameter was deprecated in v4.0.0 and will be removed in
112112
v5.0.0. After removal, the parse_*, dump, save and instantiate_classes
113113
methods will only return Namespace and/or accept Namespace objects. If
114114
needed for some use case, config objects can be converted to a nested dict
115115
using the Namespace.as_dict method.
116116
"""
117+
message_with_meta = """
118+
``with_meta`` parameter was deprecated in v4.44.0 and will be removed in
119+
v5.0.0. After removal, config objects will always include metadata. To
120+
remove metadata from a config object, do ``.clone(with_meta=False)``.
121+
"""
117122

118123
# Patch __init__
119124
def patched_init(self, *args, parse_as_dict: bool = False, **kwargs):
120125
self._parse_as_dict = parse_as_dict
121126
if parse_as_dict:
122-
deprecation_warning(patched_init, message)
127+
deprecation_warning(patched_init, message_parse_as_dict)
123128
self._unpatched_init(*args, **kwargs)
124129

125130
ArgumentParser._unpatched_init = ArgumentParser.__init__
@@ -129,9 +134,21 @@ def patched_init(self, *args, parse_as_dict: bool = False, **kwargs):
129134
def patch_parse_method(method_name):
130135
unpatched_method_name = "_unpatched_" + method_name
131136

132-
def patched_parse(self, *args, _skip_validation: bool = False, **kwargs) -> Union[Namespace, Dict[str, Any]]:
137+
def patched_parse(
138+
self,
139+
*args,
140+
with_meta: Optional[bool] = None,
141+
_skip_validation: bool = False,
142+
**kwargs,
143+
) -> Union[Namespace, Dict[str, Any]]:
133144
parse_method = getattr(self, unpatched_method_name)
134145
cfg = parse_method(*args, _skip_validation=_skip_validation, **kwargs)
146+
147+
if isinstance(with_meta, bool):
148+
deprecation_warning(patched_parse, message_with_meta)
149+
if not (with_meta or (with_meta is None and self._default_meta)):
150+
cfg = cfg.clone(with_meta=False)
151+
135152
return cfg.as_dict() if self._parse_as_dict and not _skip_validation else cfg
136153

137154
setattr(ArgumentParser, unpatched_method_name, getattr(ArgumentParser, method_name))
@@ -539,12 +556,23 @@ def deprecation_warning_error_handler(stacklevel):
539556
deprecation_warning("ArgumentParser.error_handler", error_handler_message, stacklevel=stacklevel)
540557

541558

559+
default_meta_message = """
560+
``default_meta`` property was deprecated in v4.44.0 and will be removed in
561+
v5.0.0. After removal, config objects will always include metadata. To
562+
remove metadata from a config object, do ``.clone(with_meta=False)``.
563+
"""
564+
565+
542566
class ParserDeprecations:
543567
"""Helper class for ArgumentParser deprecations. Will be removed in v5.0.0."""
544568

545-
def __init__(self, *args, error_handler=False, **kwargs):
569+
def __init__(self, *args, error_handler=False, default_meta=None, **kwargs):
546570
super().__init__(*args, **kwargs)
547571
self.error_handler = error_handler
572+
if default_meta is None:
573+
self._default_meta = True
574+
else:
575+
self.default_meta = default_meta
548576

549577
@property
550578
@deprecated("error_handler property is deprecated and will be removed in v5.0.0.")
@@ -572,6 +600,27 @@ def error_handler(self, error_handler):
572600
else:
573601
raise ValueError("error_handler can be either a Callable or None.")
574602

603+
@property
604+
@deprecated(default_meta_message)
605+
def default_meta(self) -> bool:
606+
"""Whether by default metadata is included in config objects.
607+
608+
:getter: Returns the current default metadata setting.
609+
:setter: Sets the default metadata setting.
610+
611+
Raises:
612+
ValueError: If an invalid value is given.
613+
"""
614+
return self._default_meta
615+
616+
@default_meta.setter
617+
def default_meta(self, default_meta: bool):
618+
if isinstance(default_meta, bool):
619+
deprecation_warning("ArgumentParser.default_meta", default_meta_message)
620+
self._default_meta = default_meta
621+
else:
622+
raise ValueError("default_meta expects a boolean.")
623+
575624
@deprecated(
576625
"""
577626
instantiate_subclasses was deprecated in v4.0.0 and will be removed in v5.0.0.

0 commit comments

Comments
 (0)