Skip to content

container

Parses Container Pydantic Fields to Command-Line Arguments.

The container 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 container pydantic model fields to ArgumentParser command-line arguments.

should_parse(field)

Checks whether the field should be parsed as a container.

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 container.

Source code in pydantic_argparse/parsers/container.py
def should_parse(field: pydantic.fields.ModelField) -> bool:
    """Checks whether the field should be parsed as a `container`.

    Args:
        field (pydantic.fields.ModelField): Field to check.

    Returns:
        bool: Whether the field should be parsed as a `container`.
    """
    # Check and Return
    return utils.types.is_field_a(field, collections.abc.Container) and not utils.types.is_field_a(
        field, (collections.abc.Mapping, enum.Enum, str, bytes)
    )

parse_field(parser, field)

Adds container 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/container.py
def parse_field(
    parser: argparse.ArgumentParser,
    field: pydantic.fields.ModelField,
) -> Optional[utils.pydantic.PydanticValidator]:
    """Adds container 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 Container Field
    parser.add_argument(
        utils.arguments.name(field),
        action=argparse._StoreAction,
        nargs=argparse.ONE_OR_MORE,
        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: v)