Skip to content

Commit

Permalink
Some linting and doc stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
fkglr committed Nov 13, 2024
1 parent 1eebc45 commit 0bb9795
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 45 deletions.
33 changes: 7 additions & 26 deletions vendor/pydantic-argparse/pydantic_argparse/argparse/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __init__(
exit_on_error: bool = True,
extra_defaults: dict[type, dict[str, tuple[str, Any]]] | None = None,
) -> None:
"""Instantiates the Typed Argument Parser with its `pydantic` model.
"""Instantiates the typed Argument Parser with its `pydantic` model.
:param model: Pydantic argument model class.
:param prog: Program name for CLI.
Expand Down Expand Up @@ -112,18 +112,6 @@ def __init__(
if self.version:
self._add_version_flag()

@property
def has_submodels(self) -> bool: # noqa: D102
# this is for simple nested models as arg groups
has_submodels = len(self._submodels) > 0

# this is for nested commands
if self._subcommands is not None:
has_submodels = has_submodels or any(
len(subparser._submodels) > 0 for subparser in self._subcommands.choices.values()
)
return has_submodels

def parse_typed_args(
self,
args: list[str] | None = None,
Expand All @@ -133,15 +121,8 @@ def parse_typed_args(
If `args` are not supplied by the user, then they are automatically
retrieved from the `sys.argv` command-line arguments.
Args:
args (Optional[List[str]]): Optional list of arguments to parse.
Returns:
PydanticModelT: Populated instance of typed arguments model.
Raises:
argparse.ArgumentError: Raised upon error, if not exiting on error.
SystemExit: Raised upon error, if exiting on error.
:param args: Optional list of arguments to parse.
:return: A tuple of the whole parsed model, as well as the submodel representing the selected subcommand.
"""
# Call Super Class Method
namespace = self.parse_args(args)
Expand All @@ -152,9 +133,9 @@ def parse_typed_args(
except ValidationError as exc:
# Catch exceptions, and use the ArgumentParser.error() method
# to report it to the user
self.validation_error(exc, nested_parser)
self._validation_error(exc, nested_parser)

def validation_error(self, error: ValidationError, parser: _NestedArgumentParser) -> Never:
def _validation_error(self, error: ValidationError, parser: _NestedArgumentParser) -> Never:
self.print_usage(sys.stderr)

model = parser.model
Expand Down Expand Up @@ -276,12 +257,12 @@ def _add_version_flag(self) -> None:
def _add_model(
self,
model: Type[BaseModel],
arg_group: Optional[argparse._ArgumentGroup] = None,
arg_group: argparse._ArgumentGroup | None = None,
) -> None:
"""Adds the `pydantic` model to the argument parser.
Args:
model (Type[PydanticModelT]): Pydantic model class to add to the
model (Type[BaseModel]): Pydantic model class to add to the
argument parser.
arg_group: (Optional[argparse._ArgumentGroup]): argparse ArgumentGroup.
This should not normally be passed manually, but only during
Expand Down
14 changes: 1 addition & 13 deletions vendor/pydantic-argparse/pydantic_argparse/parsers/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,6 @@
)


def should_parse(field: PydanticField) -> bool:
"""Checks whether the field should be parsed as a `command`.
Args:
field (PydanticField): Field to check.
Returns:
bool: Whether the field should be parsed as a `command`.
"""
# Check and Return
return field.is_subcommand()


def parse_field(
subparser: argparse._SubParsersAction,
field: PydanticField,
Expand All @@ -41,6 +28,7 @@ def parse_field(
Args:
subparser (argparse._SubParsersAction): Sub-parser to add to.
field (PydanticField): Field to be added to parser.
extra_defaults: Defaults coming from external sources, such as environment variables or config files.
"""
# Add Command
subparser.add_parser(
Expand Down
35 changes: 35 additions & 0 deletions vendor/pydantic-argparse/pydantic_argparse/utils/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ def __init__(
hidden: bool,
**kwargs: Unpack[_FromFieldInfoInputs],
):
"""
Creates a new ArgFieldInfo.
This is a special variant of pydantic's FieldInfo, which adds several arguments,
mainly related to CLI arguments.
For general usage and details on the generic parameters see https://docs.pydantic.dev/latest/concepts/fields.
Just as with pydantic's FieldInfo, this should usually not be called directly.
Instead use the Field() function of this module.
:param default: The default value, if non is given explicitly.
:param positional: Specifies, if the argument is shown as positional, as opposed to optional (default), on the CLI.
:param short: An optional alternative name for the CLI, which is auto-prefixed with "-".
:param metavar: The type hint which is shown on the CLI for an argument. If none is specified, it is automatically inferred from its type.
:param cli_group: The group in the CLI under which the argument is listed.
:param const: Specifies, a default value, if the argument is set with no explicit value.
:param hidden: Specifies, that the argument is part of neither the CLI nor the config file.
:param kwargs: Generic pydantic Field() arguments (see https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.FieldInfo).
"""
super().__init__(default=default, **kwargs)

self.positional = positional
Expand All @@ -40,4 +58,21 @@ def Field(
hidden: bool = False,
**kwargs: Unpack[_FromFieldInfoInputs],
) -> Any:
"""
Creates a new ArgFieldInfo.
This is a special variant of pydantic's Field() function, which adds several arguments,
mainly related to CLI arguments.
For general usage and details on the generic parameters see https://docs.pydantic.dev/latest/concepts/fields.
:param default: The default value, if non is given explicitly.
:param positional: Specifies, if the argument is shown as positional, as opposed to optional (default), on the CLI.
:param short: An optional alternative name for the CLI, which is auto-prefixed with "-".
:param metavar: The type hint which is shown on the CLI for an argument. If none is specified, it is automatically inferred from its type.
:param cli_group: The group in the CLI under which the argument is listed.
:param const: Specifies, a default value, if the argument is set with no explicit value.
:param hidden: Specifies, that the argument is part of neither the CLI nor the config file.
:param kwargs: Generic pydantic Field() arguments (see https://docs.pydantic.dev/latest/api/fields/#pydantic.fields.Field).
:return: A ConfigArgFieldInfo.
"""
return ArgFieldInfo(default, positional, short, metavar, group, const, hidden, **kwargs)
13 changes: 7 additions & 6 deletions vendor/pydantic-argparse/pydantic_argparse/utils/pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
Annotated,
)

from mypyc.ir.ops import Assign
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from pydantic_core import PydanticUndefined
Expand Down Expand Up @@ -77,7 +78,7 @@ def _get_type(self, annotation: type | None) -> type | tuple[type | None, ...] |
elif origin is None:
types = [annotation]
else:
assert False, f"Unsupported origin {origin} for field {self.name} with annotation {annotation}"
raise AssertionError(f"Unsupported origin {origin} for field {self.name} with annotation {annotation}")

base_types: list[Type | None] = []

Expand All @@ -99,10 +100,9 @@ def _get_type(self, annotation: type | None) -> type | tuple[type | None, ...] |
return tuple(base_types)

def get_type(self) -> type | tuple[type | None, ...] | None:
"""Return the type annotation for the `pydantic` field.
"""Return the mainly interesting types according to the type annotation (in the context of argument parsing).
Returns:
Union[Type, Tuple[Type, ...], None]
Returns: One or more types (potentially None).
"""
annotation = self.info.annotation
return self._get_type(annotation)
Expand Down Expand Up @@ -202,12 +202,13 @@ def is_subcommand(self) -> bool:
def arg_names(self, invert: bool = False) -> tuple[str, str] | tuple[str]:
"""Standardises argument name when printing to command line.
This also includes potential short names if specified.
Args:
invert (bool): Whether to invert the name by prepending `--no-`.
Returns:
str: Standardised name of the argument. Checks `pydantic.Field` title first,
but defaults to the field name.
str: Standardised name of the argument.
"""
name = self.info.title or self.name

Expand Down

0 comments on commit 0bb9795

Please sign in to comment.