Add arguments from a pydantic model to an argparse parser.
(parser: argparse.ArgumentParser, model: Type[BaseModel])
| 80 | |
| 81 | |
| 82 | def add_args_from_model(parser: argparse.ArgumentParser, model: Type[BaseModel]): |
| 83 | """Add arguments from a pydantic model to an argparse parser.""" |
| 84 | |
| 85 | for name, field in model.model_fields.items(): |
| 86 | description = field.description |
| 87 | if field.default and description and not field.is_required(): |
| 88 | description += f" (default: {field.default})" |
| 89 | base_type = ( |
| 90 | _get_base_type(field.annotation) if field.annotation is not None else str |
| 91 | ) |
| 92 | list_type = _contains_list_type(field.annotation) |
| 93 | dict_type = _contains_dict_type(field.annotation) |
| 94 | if dict_type: |
| 95 | parser.add_argument( |
| 96 | f"--{name}", |
| 97 | dest=name, |
| 98 | type=_parse_json_object_arg, |
| 99 | help=description, |
| 100 | ) |
| 101 | elif base_type is not bool: |
| 102 | parser.add_argument( |
| 103 | f"--{name}", |
| 104 | dest=name, |
| 105 | nargs="*" if list_type else None, |
| 106 | type=base_type, |
| 107 | help=description, |
| 108 | ) |
| 109 | if base_type is bool: |
| 110 | parser.add_argument( |
| 111 | f"--{name}", |
| 112 | dest=name, |
| 113 | type=_parse_bool_arg, |
| 114 | help=f"{description}", |
| 115 | ) |
| 116 | |
| 117 | |
| 118 | T = TypeVar("T", bound=Type[BaseModel]) |
no test coverage detected
searching dependent graphs…