Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ Changed
for the corresponding parser/subcommand (`#809
<https://github.com/omni-us/jsonargparse/pull/809>`__).

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


v4.43.0 (2025-11-11)
--------------------
Expand Down
2 changes: 1 addition & 1 deletion jsonargparse/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def auto_cli(
if unexpected:
raise ValueError(f"Unexpected components, not class or function: {unexpected}")

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

if not isinstance(components, (list, dict)):
Expand Down
53 changes: 5 additions & 48 deletions jsonargparse/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,6 @@ def __init__(
dump_header: Optional[list[str]] = None,
default_config_files: Optional[list[Union[str, os.PathLike]]] = None,
default_env: bool = False,
default_meta: bool = True,
**kwargs,
) -> None:
"""Initializer for ArgumentParser instance.
Expand All @@ -261,7 +260,6 @@ def __init__(
dump_header: Header to include as comment when dumping a config object.
default_config_files: Default config file locations, e.g. ``['~/.config/myapp/*.yaml']``.
default_env: Set the default value on whether to parse environment variables.
default_meta: Set the default value on whether to include metadata in config objects.
"""
super().__init__(*args, formatter_class=formatter_class, logger=logger, **kwargs)
self._group_class = get_argument_group_class(self)
Expand All @@ -271,7 +269,6 @@ def __init__(
self.required_args: set[str] = set()
self.save_path_content: set[str] = set()
self.default_config_files = default_config_files
self.default_meta = default_meta
self.default_env = default_env
self.env_prefix = env_prefix
self.parser_mode = parser_mode
Expand Down Expand Up @@ -340,7 +337,6 @@ def _parse_common(
cfg: Namespace,
env: Optional[bool],
defaults: bool,
with_meta: Optional[bool],
skip_validation: bool,
skip_required: bool = False,
skip_subcommands: bool = False,
Expand All @@ -352,7 +348,6 @@ def _parse_common(
cfg: The configuration object.
env: Whether to merge with the parsed environment, None to use parser's default.
defaults: Whether to merge with the parser's defaults.
with_meta: Whether to include metadata in config object, None to use parser's default.
skip_validation: Whether to skip validation of configuration.
skip_required: Whether to skip check of required arguments.
skip_subcommands: Whether to skip subcommand processing.
Expand Down Expand Up @@ -387,9 +382,6 @@ def _parse_common(
if not skip_validation:
self.validate(cfg, skip_required=skip_required)

if not (with_meta or (with_meta is None and self._default_meta)):
cfg = cfg.clone(with_meta=False)

return cfg

def _parse_defaults_and_environ(
Expand Down Expand Up @@ -417,7 +409,6 @@ def parse_args( # type: ignore[override]
namespace: Optional[Namespace] = None,
env: Optional[bool] = None,
defaults: bool = True,
with_meta: Optional[bool] = None,
**kwargs,
) -> Namespace:
"""Parses command line argument strings.
Expand All @@ -430,7 +421,6 @@ def parse_args( # type: ignore[override]
args: List of arguments to parse or None to use sys.argv.
env: Whether to merge with the parsed environment, None to use parser's default.
defaults: Whether to merge with the parser's defaults.
with_meta: Whether to include metadata in config object, None to use parser's default.

Returns:
A config object with all parsed values.
Expand Down Expand Up @@ -465,7 +455,6 @@ def parse_args( # type: ignore[override]
cfg=cfg,
env=env,
defaults=defaults,
with_meta=with_meta,
skip_validation=skip_validation,
)

Expand All @@ -481,7 +470,6 @@ def parse_object(
cfg_base: Optional[Namespace] = None,
env: Optional[bool] = None,
defaults: bool = True,
with_meta: Optional[bool] = None,
**kwargs,
) -> Namespace:
"""Parses configuration given as an object.
Expand All @@ -490,7 +478,6 @@ def parse_object(
cfg_obj: The configuration object.
env: Whether to merge with the parsed environment, None to use parser's default.
defaults: Whether to merge with the parser's defaults.
with_meta: Whether to include metadata in config object, None to use parser's default.

Returns:
A config object with all parsed values.
Expand All @@ -513,7 +500,6 @@ def parse_object(
cfg=cfg,
env=env,
defaults=defaults,
with_meta=with_meta,
skip_validation=skip_validation,
skip_required=skip_required,
)
Expand Down Expand Up @@ -558,15 +544,13 @@ def parse_env(
self,
env: Optional[dict[str, str]] = None,
defaults: bool = True,
with_meta: Optional[bool] = None,
**kwargs,
) -> Namespace:
"""Parses environment variables.

Args:
env: The environment object to use, if None `os.environ` is used.
defaults: Whether to merge with the parser's defaults.
with_meta: Whether to include metadata in config object, None to use parser's default.

Returns:
A config object with all parsed values.
Expand All @@ -582,7 +566,6 @@ def parse_env(
kwargs = {
"env": True,
"defaults": defaults,
"with_meta": with_meta,
"skip_validation": skip_validation,
"skip_subcommands": skip_subcommands,
}
Expand All @@ -603,7 +586,6 @@ def parse_path(
ext_vars: Optional[dict] = None,
env: Optional[bool] = None,
defaults: bool = True,
with_meta: Optional[bool] = None,
**kwargs,
) -> Namespace:
"""Parses a configuration file given its path.
Expand All @@ -613,7 +595,6 @@ def parse_path(
ext_vars: Optional external variables used for parsing jsonnet.
env: Whether to merge with the parsed environment, None to use parser's default.
defaults: Whether to merge with the parser's defaults.
with_meta: Whether to include metadata in config object, None to use parser's default.

Returns:
A config object with all parsed values.
Expand All @@ -625,12 +606,11 @@ def parse_path(
with change_to_path_dir(fpath):
cfg_str = fpath.get_content()
parsed_cfg = self.parse_string(
cfg_str,
os.path.basename(cfg_path),
ext_vars,
env,
defaults,
with_meta,
cfg_str=cfg_str,
cfg_path=os.path.basename(cfg_path),
ext_vars=ext_vars,
env=env,
defaults=defaults,
**kwargs,
)

Expand All @@ -644,7 +624,6 @@ def parse_string(
ext_vars: Optional[dict] = None,
env: Optional[bool] = None,
defaults: bool = True,
with_meta: Optional[bool] = None,
**kwargs,
) -> Namespace:
"""Parses configuration given as a string.
Expand All @@ -655,7 +634,6 @@ def parse_string(
ext_vars: Optional external variables used for parsing jsonnet.
env: Whether to merge with the parsed environment, None to use parser's default.
defaults: Whether to merge with the parser's defaults.
with_meta: Whether to include metadata in config object, None to use parser's default.

Returns:
A config object with all parsed values.
Expand All @@ -679,7 +657,6 @@ def parse_string(
cfg=cfg,
env=env,
defaults=defaults,
with_meta=with_meta,
skip_validation=skip_validation,
fail_no_subcommand=fail_no_subcommand,
)
Expand Down Expand Up @@ -1051,7 +1028,6 @@ def get_defaults(self, skip_validation: bool = False, **kwargs) -> Namespace:
cfg=cfg,
env=False,
defaults=False,
with_meta=None,
skip_validation=skip_validation,
skip_required=True,
)
Expand Down Expand Up @@ -1555,25 +1531,6 @@ def default_env(self, default_env: bool):
for subparser in self._subcommands_action._name_parser_map.values():
subparser.default_env = self._default_env

@property
def default_meta(self) -> bool:
"""Whether by default metadata is included in config objects.

:getter: Returns the current default metadata setting.
:setter: Sets the default metadata setting.

Raises:
ValueError: If an invalid value is given.
"""
return self._default_meta

@default_meta.setter
def default_meta(self, default_meta: bool):
if isinstance(default_meta, bool):
self._default_meta = default_meta
else:
raise ValueError("default_meta expects a boolean.")

@property
def env_prefix(self) -> Union[bool, str]:
"""The environment variables prefix property.
Expand Down
57 changes: 53 additions & 4 deletions jsonargparse/_deprecated.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,19 +107,24 @@ def parse_as_dict_patch():

assert not hasattr(ArgumentParser, "_unpatched_init")

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

# Patch __init__
def patched_init(self, *args, parse_as_dict: bool = False, **kwargs):
self._parse_as_dict = parse_as_dict
if parse_as_dict:
deprecation_warning(patched_init, message)
deprecation_warning(patched_init, message_parse_as_dict)
self._unpatched_init(*args, **kwargs)

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

def patched_parse(self, *args, _skip_validation: bool = False, **kwargs) -> Union[Namespace, Dict[str, Any]]:
def patched_parse(
self,
*args,
with_meta: Optional[bool] = None,
_skip_validation: bool = False,
**kwargs,
) -> Union[Namespace, Dict[str, Any]]:
parse_method = getattr(self, unpatched_method_name)
cfg = parse_method(*args, _skip_validation=_skip_validation, **kwargs)

if isinstance(with_meta, bool):
deprecation_warning(patched_parse, message_with_meta)
if not (with_meta or (with_meta is None and self._default_meta)):
cfg = cfg.clone(with_meta=False)

return cfg.as_dict() if self._parse_as_dict and not _skip_validation else cfg

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


default_meta_message = """
``default_meta`` property was deprecated in v4.44.0 and will be removed in
v5.0.0. After removal, config objects will always include metadata. To
remove metadata from a config object, do ``.clone(with_meta=False)``.
"""


class ParserDeprecations:
"""Helper class for ArgumentParser deprecations. Will be removed in v5.0.0."""

def __init__(self, *args, error_handler=False, **kwargs):
def __init__(self, *args, error_handler=False, default_meta=None, **kwargs):
super().__init__(*args, **kwargs)
self.error_handler = error_handler
if default_meta is None:
self._default_meta = True
else:
self.default_meta = default_meta

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

@property
@deprecated(default_meta_message)
def default_meta(self) -> bool:
"""Whether by default metadata is included in config objects.

:getter: Returns the current default metadata setting.
:setter: Sets the default metadata setting.

Raises:
ValueError: If an invalid value is given.
"""
return self._default_meta

@default_meta.setter
def default_meta(self, default_meta: bool):
if isinstance(default_meta, bool):
deprecation_warning("ArgumentParser.default_meta", default_meta_message)
self._default_meta = default_meta
else:
raise ValueError("default_meta expects a boolean.")

@deprecated(
"""
instantiate_subclasses was deprecated in v4.0.0 and will be removed in v5.0.0.
Expand Down
Loading
Loading