mapping
Parses Mapping Pydantic Fields to Command-Line Arguments.
The mapping
module contains the should_parse
function, which checks whether
this module should be used to parse the field, as well as the parse_field
function, which parses mapping pydantic
model fields to ArgumentParser
command-line arguments.
should_parse(field)
Checks whether the field should be parsed as a mapping
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
field |
pydantic.fields.ModelField |
Field to check. |
required |
Returns:
Type | Description |
---|---|
bool |
Whether the field should be parsed as a |
Source code in pydantic_argparse/parsers/mapping.py
def should_parse(field: pydantic.fields.ModelField) -> bool:
"""Checks whether the field should be parsed as a `mapping`.
Args:
field (pydantic.fields.ModelField): Field to check.
Returns:
bool: Whether the field should be parsed as a `mapping`.
"""
# Check and Return
return utils.types.is_field_a(field, collections.abc.Mapping)
parse_field(parser, field)
Adds mapping pydantic field to argument parser.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parser |
argparse.ArgumentParser |
Argument parser to add to. |
required |
field |
pydantic.fields.ModelField |
Field to be added to parser. |
required |
Returns:
Type | Description |
---|---|
Optional[utils.pydantic.PydanticValidator] |
Possible validator method. |
Source code in pydantic_argparse/parsers/mapping.py
def parse_field(
parser: argparse.ArgumentParser,
field: pydantic.fields.ModelField,
) -> Optional[utils.pydantic.PydanticValidator]:
"""Adds mapping pydantic field to argument parser.
Args:
parser (argparse.ArgumentParser): Argument parser to add to.
field (pydantic.fields.ModelField): Field to be added to parser.
Returns:
Optional[utils.pydantic.PydanticValidator]: Possible validator method.
"""
# Add Mapping Field
parser.add_argument(
utils.arguments.name(field),
action=argparse._StoreAction,
help=utils.arguments.description(field),
dest=field.alias,
metavar=field.alias.upper(),
required=bool(field.required),
)
# Construct and Return Validator
return utils.pydantic.as_validator(field, lambda v: ast.literal_eval(v))