Skip to content

InputArgs

InputArgs is a model that represents the input arguments of an application. After it is initialized the parse_args method can be called to parse the arguments and return them as a dictionary.

Attributes:

Name Type Description
prefix UpperCase

The prefix to use for environment variables. Defaults to "ATRO_ARGS". This means that the environment variable for the argument "name" will be "ATRO_ARGS_NAME" and the environment variable for the argument "other_names" will be "ATRO_ARGS_OTHER_NAMES".

args list[Arg]

A list of arguments to parse. Defaults to [].

sources list[ArgSource | Path]

(list[ArgSource], optional): A list of ArgSource enums or paths that represent sources to source arguments from. Defaults to [ArgSource.cli_args, Path(".env"), ArgSource.envs]. Order decides the priority in which the arguments are sourced. For example if cli_args is before envs then cli_args will have priority over envs.

get_dict

get_dict(cli_input_args=None)

Parses the arguments and returns them as a dictionary from (potentially) multiple sources.

Examples:

>>> from atro_core.args import InputArgs, Arg
>>> input_arg = InputArgs()
>>> input_arg.add_arg(Arg(name="a", arg_type=float, help="The first addend in the addition."))
>>> input_arg.get_dict()
{'a': 1.23}

Parameters:

Name Type Description Default
cli_input_args Sequence[str]

A list of strings representing the CLI arguments. Defaults to None which means the arguments will be read from sys.argv which is almost always the desired behaviour.

None

Returns:

Type Description
dict[str, Any]

A dictionary with keys being the argument names and values being the argument values. Argument values will be of the type specified in the Arg model.

Source code in atro_core/args/input_args.py
def get_dict(self, cli_input_args: Sequence[str] | None = None) -> dict[str, Any]:
    """Parses the arguments and returns them as a dictionary from (potentially) multiple sources.

    Examples:
        >>> from atro_core.args import InputArgs, Arg
        >>> input_arg = InputArgs()
        >>> input_arg.add_arg(Arg(name="a", arg_type=float, help="The first addend in the addition."))
        >>> input_arg.get_dict()
        {'a': 1.23}

    Args:
        cli_input_args (Sequence[str]): A list of strings representing the CLI arguments. Defaults to None which means the arguments will be read from sys.argv which is almost always the desired behaviour.

    Returns:
        A dictionary with keys being the argument names and values being the argument values. Argument values will be of the type specified in the Arg model.
    """

    model: dict[str, str] = {}

    for source in self.sources:
        args = load_source(source, self.prefix, self.args, cli_input_args)
        model = merge_dicts(
            model,
            args,
            overwrite=False,
            current_name=source.value if isinstance(source, ArgSource) else source.as_posix(),
            updating_dict_name="args",
        )

    model = restrict_keys(model, self.args)
    typed_model = cast_dict_based_on_args(model, self.args)
    typed_model = merge_dicts(
        typed_model,
        {arg.name: arg.default for arg in self.args},
        overwrite=False,
        current_name="defaults",
        updating_dict_name="args",
    )
    throw_if_required_not_populated(typed_model, self.args)

    return typed_model

get_cls

get_cls(class_type, cli_input_args=None)

Parses the arguments and returns them as an instance of the given class with the data populated from (potentially) multiple sources.

Examples:

>>> input_args = InputArgs(prefix="ATRO_TEST")
>>> input_args.set_source(Path(__file__).parent / ".env")
>>> resp = input_args.add_cls(TestClassWithUnionType)
>>> resp = input_args.get_cls(TestClassWithUnionType)
>>> resp.random_env_file_number
10

Parameters:

Name Type Description Default
class_type type

Either a pydantic class or dataclass that we want to populate. Note the arguments have to be added before for this to work, either by .add_cls or by adding arguments one by one.

required
cli_input_args Sequence[str]

A list of strings representing the CLI arguments. Defaults to None which means the arguments will be read from sys.argv which is almost always the desired behaviour.

None

Returns:

Type Description
T

Instance of the class provided with the fielids populated from potentially multiple sources.

Source code in atro_core/args/input_args.py
def get_cls(self, class_type: type[T], cli_input_args: Sequence[str] | None = None) -> T:
    """Parses the arguments and returns them as an instance of the given class with the data populated from (potentially) multiple sources.

    Examples:
        >>> input_args = InputArgs(prefix="ATRO_TEST")
        >>> input_args.set_source(Path(__file__).parent / ".env")
        >>> resp = input_args.add_cls(TestClassWithUnionType)
        >>> resp = input_args.get_cls(TestClassWithUnionType)
        >>> resp.random_env_file_number
        10

    Args:
        class_type (type): Either a pydantic class or dataclass that we want to populate. Note the arguments have to be added before for this to work, either by .add_cls or by adding arguments one by one.
        cli_input_args (Sequence[str]): A list of strings representing the CLI arguments. Defaults to None which means the arguments will be read from sys.argv which is almost always the desired behaviour.

    Returns:
        Instance of the class provided with the fielids populated from potentially multiple sources.
    """
    typed_dict = self.get_dict(cli_input_args=cli_input_args)

    if is_dataclass(class_type):
        return get_dataclass(typed_dict, class_type, cli_input_args=cli_input_args)  # type: ignore
    elif issubclass(class_type, BaseModel):
        return get_pydantic(typed_dict, class_type, cli_input_args=cli_input_args)  # type: ignore
    else:
        raise Exception(f"Class type '{class_type}' is not supported.")

populate_cls

populate_cls(class_type, cli_input_args=None)

Parses the arguments and returns them as an instance of the given class with the data populated from (potentially) multiple sources.

Examples:

>>> input_args = InputArgs(prefix="ATRO_TEST")
>>> input_args.set_source(Path(__file__).parent / ".env")
>>> resp = input_args.populate_cls(TestClassWithUnionType)
>>> resp.random_env_file_number
10

Parameters:

Name Type Description Default
class_type type

Either a pydantic class or dataclass that we want to populate.

required
cli_input_args Sequence[str]

A list of strings representing the CLI arguments. Defaults to None which means the arguments will be read from sys.argv which is almost always the desired behaviour.

None

Returns:

Type Description
T

Instance of the class provided with the fielids populated from potentially multiple sources.

Source code in atro_core/args/input_args.py
def populate_cls(self, class_type: type[T], cli_input_args: Sequence[str] | None = None) -> T:
    """Parses the arguments and returns them as an instance of the given class with the data populated from (potentially) multiple sources.

    Examples:
        >>> input_args = InputArgs(prefix="ATRO_TEST")
        >>> input_args.set_source(Path(__file__).parent / ".env")
        >>> resp = input_args.populate_cls(TestClassWithUnionType)
        >>> resp.random_env_file_number
        10

    Args:
        class_type (type): Either a pydantic class or dataclass that we want to populate.
        cli_input_args (Sequence[str]): A list of strings representing the CLI arguments. Defaults to None which means the arguments will be read from sys.argv which is almost always the desired behaviour.

    Returns:
        Instance of the class provided with the fielids populated from potentially multiple sources.
    """
    self.add_cls(class_type)
    return self.get_cls(class_type, cli_input_args=cli_input_args)

Arg

Arg is a model that represents a single argument that can be passed to a program via CLI, ENV, ENV file or Yaml file.

Attributes:

Name Type Description
name str

The name of the argument. This is the key that will be used to access the value of the argument.

other_names list[str]

Other names that can be used to access the value of the argument. Defaults to [].

arg_type type

The type of the argument. Defaults to str. Possible values are: str, int, float, bool, list, dict, no generic typing allowed, e.g. list[str] is not allowed.

help str

The help text for the argument. Defaults to "".

required bool

Whether the argument is required. Defaults to True.

default Any

The default value of the argument. If set to None it is assumed there is no default (will fail on required=True). Defaults to None.

ArgSource

Enum for the non-file source of an argument. This doesn't included sources that are file based.

Attributes:

Name Type Description
value str

The value of the enum. Possible choices are "cli" or "envs".