From d50c0262dddcb06ad72cacaecf113a2874c72f0c Mon Sep 17 00:00:00 2001 From: Tim Paine <3105306+timkpaine@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:51:12 -0500 Subject: [PATCH] Apply only passed arguments and warn about skipped fields on use parse_extra_args_model warned at parse time about each field it could not map to an argument, including empty lists of models, so a plugin built on it printed the same warnings in each build. The reasons are now logged at debug level, and a warning is printed only when an argument for a skipped field is passed. It also applied the default of each argument that was not passed. That reset a falsy value on the instance to the field default, replaced indexed list arguments with the list default, and printed a validation warning for optional dict fields. Arguments that are not passed are now left out of the parsed result. create_model_parser keeps its defaults. Lists of paths are supported like lists of strings. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --- README.md | 2 + p2a/model.py | 104 ++++++++++++++++++++++++++++++---------- p2a/tests/test_model.py | 63 ++++++++++++++++++++++-- 3 files changed, 140 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index e895782..454a0f1 100644 --- a/README.md +++ b/README.md @@ -31,5 +31,7 @@ parse_extra_args_model(model, sys.argv) For integration with existing `argparse` CLIs, a helper function to create an `argparse.SubParser` is also provided: `p2a.create_model_parser`. +Fields with types that cannot be mapped to arguments are skipped. `parse_extra_args_model` warns about a skipped field only when an argument for it is passed. + > [!NOTE] > This library was generated using [copier](https://copier.readthedocs.io/en/stable/) from the [Base Python Project Template repository](https://github.com/python-project-templates/base). diff --git a/p2a/model.py b/p2a/model.py index 693819d..f0eb486 100644 --- a/p2a/model.py +++ b/p2a/model.py @@ -1,5 +1,5 @@ import sys -from argparse import ArgumentParser +from argparse import SUPPRESS, ArgumentParser from enum import Enum from logging import Logger from pathlib import Path @@ -34,6 +34,9 @@ def _initlog(level: str = "WARNING"): def _add_argument(parser: ArgumentParser, name: str, arg_type: type, default_value, **kwargs): _log.debug(f"Adding argument: {name:<75} - {arg_type!s:<10} - {default_value!s:<10}") + if parser.argument_default is SUPPRESS: + # Leave unpassed arguments out of the parsed result + default_value = SUPPRESS if "action" in kwargs: parser.add_argument(name, default=default_value, action=kwargs["action"]) else: @@ -59,14 +62,26 @@ def _is_supported_type(field_type: type) -> bool: return all(isinstance(arg, (str, int, float, bool, Enum)) for arg in get_args(field_type)) if not isinstance(field_type, type): return False - return field_type in (str, int, float, bool) or issubclass(field_type, Enum) + return field_type in (str, int, float, bool) or issubclass(field_type, (Enum, Path)) -def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type["BaseModel"]], prefix: str = ""): +def _skip_field(unsupported: dict[str, str], arg_name: str, message: str): + # Remember why a field has no argument, so we can warn if one is passed for it + _log.debug(message) + unsupported[arg_name] = message + + +def _recurse_add_fields( + parser: ArgumentParser, model: Union["BaseModel", type["BaseModel"]], prefix: str = "", unsupported: dict[str, str] | None = None +): # Model is required if model is None: raise ValueError("Model instance cannot be None") # coverage: ignore + # Fields we cannot expose, by argument name + if unsupported is None: + unsupported = {} + # Extract the fields from a model instance or class if isinstance(model, type): model_fields = model.model_fields @@ -94,7 +109,7 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" if len(non_none_types) == 1: field_type = non_none_types[0] else: - _log.warning(f"Unsupported Union type for argument '{field_name}': {field_type}") + _skip_field(unsupported, arg_name, f"Unsupported Union type for argument '{field_name}': {field_type}") continue # Default value, promote PydanticUndefined to None @@ -146,19 +161,21 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" ############################ # MARK: instance(BaseModel) # Nested model, add its fields with a prefix - _recurse_add_fields(parser, field_instance, prefix=f"{field_name}.") + _recurse_add_fields(parser, field_instance, prefix=f"{field_name}.", unsupported=unsupported) elif isinstance(field_type, type) and issubclass(field_type, BaseModel): ######################## # MARK: type(BaseModel) # Nested model class, add its fields with a prefix - _recurse_add_fields(parser, field_type, prefix=f"{field_name}.") + _recurse_add_fields(parser, field_type, prefix=f"{field_name}.", unsupported=unsupported) elif get_origin(field_type) is Literal: ################ # MARK: Literal literal_args = get_args(field_type) if not all(isinstance(arg, (str, int, float, bool, Enum)) for arg in literal_args): # Only support simple literal types for now - _log.warning(f"Only Literal types of str, int, float, or bool are supported - field `{field_name}` got {literal_args}") + _skip_field( + unsupported, arg_name, f"Only Literal types of str, int, float, or bool are supported - field `{field_name}` got {literal_args}" + ) continue #################################### # MARK: Literal[str|int|float|bool] @@ -173,7 +190,7 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" if isinstance(value, BaseModel): ######################## # MARK: List[BaseModel] - _recurse_add_fields(parser, value, prefix=f"{field_name}.{i}.") + _recurse_add_fields(parser, value, prefix=f"{field_name}.{i}.", unsupported=unsupported) continue else: ######################## @@ -187,7 +204,11 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" continue # If there's nothing here, we don't know how to address them # TODO: we could just prefill e.g. --field.0, --field.1 up to some limit - _log.warning(f"Only lists of str, int, float, or bool are supported - field `{field_name}` got {get_args(field_type)[0]}") + _skip_field( + unsupported, + arg_name, + f"Only lists of str, int, float, or bool are supported - field `{field_name}` got {get_args(field_type)[0]}", + ) continue if field_instance: for i, value in enumerate(field_instance): @@ -214,7 +235,11 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" if not _is_supported_type(key_type): # Check Key type, must be str, int, float, bool, enum - _log.warning(f"Only dicts with str, int, float, bool, or enum keys are supported - field `{field_name}` got key type {key_type}") + _skip_field( + unsupported, + arg_name, + f"Only dicts with str, int, float, bool, or enum keys are supported - field `{field_name}` got key type {key_type}", + ) continue if isinstance(key_type, type) and issubclass(key_type, Enum): @@ -222,8 +247,10 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" if not _is_supported_type(value_type) and not (isinstance(value_type, type) and issubclass(value_type, BaseModel)): # Unsupported value type - _log.warning( - f"Only dicts with str, int, float, bool, enum, or BaseModel values are supported - field `{field_name}` got value type {value_type}" + _skip_field( + unsupported, + arg_name, + f"Only dicts with str, int, float, bool, enum, or BaseModel values are supported - field `{field_name}` got value type {value_type}", ) continue @@ -234,8 +261,15 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" for enum_key in key_type: if not field_instance or enum_key not in field_instance: continue - _recurse_add_fields(parser, (field_instance or {}).get(enum_key, value_type), prefix=f"{field_name}.{enum_key.name}.") - _recurse_add_fields(parser, (field_instance or {}).get(enum_key, value_type), prefix=f"{field_name}.{enum_key.value}.") + _recurse_add_fields( + parser, (field_instance or {}).get(enum_key, value_type), prefix=f"{field_name}.{enum_key.name}.", unsupported=unsupported + ) + _recurse_add_fields( + parser, + (field_instance or {}).get(enum_key, value_type), + prefix=f"{field_name}.{enum_key.value}.", + unsupported=unsupported, + ) elif _is_supported_type(value_type): # Add directly @@ -259,8 +293,10 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" if not _is_supported_type(value_type) and not field_instance: # Check Value type, must be str, int, float, bool if an instance isnt provided - _log.warning( - f"Only dicts with str, int, float, bool, or enum values are supported - field `{field_name}` got value type {value_type}" + _skip_field( + unsupported, + arg_name, + f"Only dicts with str, int, float, bool, or enum values are supported - field `{field_name}` got value type {value_type}", ) continue @@ -273,12 +309,16 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" if isinstance(key, Enum): # Already handled above continue - _recurse_add_fields(parser, value, prefix=f"{field_name}.{key}.") + _recurse_add_fields(parser, value, prefix=f"{field_name}.{key}.", unsupported=unsupported) continue # If we have mixed, we don't support elif any(isinstance(v, BaseModel) for v in field_instance.values()): - _log.warning(f"Mixed dict value types are not supported - field `{field_name}` has mixed BaseModel and non-BaseModel values") + _skip_field( + unsupported, + arg_name, + f"Mixed dict value types are not supported - field `{field_name}` has mixed BaseModel and non-BaseModel values", + ) continue # If we have non BaseModel values, we can still add a parser by route @@ -312,21 +352,37 @@ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", type[" defaults.append(f"{k}={v}") _add_argument(parser=parser, name=arg_name, arg_type=str, default_value=",".join(defaults) if defaults else None) else: - _log.warning(f"Unsupported field type for argument '{field_name}': {field_type}") + _skip_field(unsupported, arg_name, f"Unsupported field type for argument '{field_name}': {field_type}") return parser -def create_model_parser(model: "BaseModel") -> ArgumentParser: +def _create_model_parser(model: "BaseModel", argument_default: Any = None) -> tuple[ArgumentParser, dict[str, str]]: # Recursively parse fields from a pydantic model and its sub-models # and create an argument parser to parse extra args - parser = ArgumentParser(prog="hatch-build-extras-model", allow_abbrev=False) - parser = _recurse_add_fields(parser, model) - return parser + parser = ArgumentParser(prog="hatch-build-extras-model", allow_abbrev=False, argument_default=argument_default) + unsupported: dict[str, str] = {} + _recurse_add_fields(parser, model, unsupported=unsupported) + return parser, unsupported + + +def create_model_parser(model: "BaseModel") -> ArgumentParser: + return _create_model_parser(model)[0] + + +def _warn_unsupported(unsupported: dict[str, str], extras: list[str]): + # Warn only about fields the caller tried to set + passed = {extra.split("=", 1)[0] for extra in extras if extra.startswith("--")} + for arg_name, message in unsupported.items(): + if any(name == arg_name or name.startswith(f"{arg_name}.") for name in passed): + _log.warning(message) def parse_extra_args_model(model: ModelT, argv: list[str] | None = None) -> tuple[ModelT, list[str]]: # Parse the extra args and update the model - args, kwargs = parse_extra_args(create_model_parser(model), argv) + # Apply only the arguments that were passed. The model already holds every default. + parser, unsupported = _create_model_parser(model, argument_default=SUPPRESS) + args, kwargs = parse_extra_args(parser, argv) + _warn_unsupported(unsupported, kwargs) for key, value in args.items(): # Handle nested fields diff --git a/p2a/tests/test_model.py b/p2a/tests/test_model.py index b680c37..5ab8ec6 100644 --- a/p2a/tests/test_model.py +++ b/p2a/tests/test_model.py @@ -179,6 +179,39 @@ def test_get_arg_from_model(self): assert model.submodel_list_instanced[0].sub_arg_literal == "z" assert model.submodel_dict_instanced["a"].sub_arg == 500 + # No argument targets a field p2a cannot expose, so nothing is warned about + assert "[p2a][WARNING]" not in mock_stderr.getvalue() + + def test_unsupported_fields_warn_only_when_passed(self): + class Model(BaseModel): + unsupported_literal: Literal[b"test"] = b"test" + unsupported_dict: dict[SubModel, str] = {} + unsupported_dict_mixed_types: dict[str, str | SubModel] = {} + unsupported_random_type: set | None = None + unsupported_submodel_list: list[SubModel] = [] + unsupported_submodel_dict: dict[str, SubModel] = {} + + argv = [ + "--unsupported-submodel-list.0.sub-arg", + "1", + "--unsupported-submodel-dict.a.sub-arg=1", + "--unsupported-literal", + "x", + "--unsupported-dict", + "a=b", + "--unsupported-dict-mixed-types", + "a=b", + "--unsupported-random-type", + "x", + ] + with patch("sys.stderr", new_callable=StringIO) as mock_stderr: + _initlog("WARNING") + parse_extra_args_model(Model(), []) + assert "[p2a][WARNING]" not in mock_stderr.getvalue() + + _, extras = parse_extra_args_model(Model(), argv) + + assert extras == argv stderr = mock_stderr.getvalue() for text in ( "[p2a][WARNING]: Only lists of str, int, float, or bool are supported - field `unsupported_submodel_list` got ", @@ -190,8 +223,28 @@ def test_get_arg_from_model(self): ): assert text in stderr stderr = stderr.replace(text, "") - if "[p2a][WARNING]" in stderr.strip(): - for line in stderr.strip().splitlines(): - if "[p2a][WARNING]" in line: - print("UNEXPECTED WARNING:", line) - assert False + assert "[p2a][WARNING]" not in stderr + + def test_list_of_paths(self): + class Model(BaseModel, validate_assignment=True): + paths: list[Path] = [] + + model, _ = parse_extra_args_model(Model(), ["--paths", "include/a.h,include/b.h"]) + assert model.paths == [Path("include/a.h"), Path("include/b.h")] + + def test_only_passed_arguments_are_applied(self): + class Model(BaseModel, validate_assignment=True): + values: list[int] = [1, 2, 3] + flag: bool = True + flags: dict[str, str | int | float | bool] | None = None + submodel: SubModel | None = None + + with patch("sys.stderr", new_callable=StringIO) as mock_stderr: + _initlog("WARNING") + model, _ = parse_extra_args_model(Model(flag=False, flags={"enabled": True}), ["--values.0", "9"]) + + assert model.values == [9, 2, 3] + assert model.flag is False + assert model.flags == {"enabled": True} + assert model.submodel is None + assert "[p2a][WARNING]" not in mock_stderr.getvalue()