A typed argument parser for Python 3.6+ scripts.
This package enables creation of argparse.ArgumentParsers
from NamedTuple
objects.
Created parsers return parsed arguments as an object of configured type, which empowers the developer with more control
over the contents and types of their scripts.
The following example may be found here.
-
Define a
NamedTuple
specifying the script's arguments:from typing import NamedTuple class Config(NamedTuple): """ A config for this script Args: number: an integer parameter which is very necessary param: some fancy string floating: a float """ number: int param: str = "some string" floating: float = 0.7
-
Create a
TypedArgumentParser
object from theConfig
class:from argtype import TypedArgumentParser parser: TypedArgumentParser[Config] = TypedArgumentParser(Config)
-
Parse the arguments and enjoy code completion and type information!
config = parser.parse_args() for n in range(config.number): print(f"{n}: {config.param}") print(config.floating * 42)
Executing this script with -h
(help) flag:
python examples/example_script.py -h
will yield the following output:
usage: example_script.py [-h] --number NUMBER [--param PARAM]
[--floating FLOATING]
A config for this script Args:
optional arguments:
-h, --help show this help message and exit
--number NUMBER an integer parameter which is very necessary
--param PARAM some fancy string
--floating FLOATING a float
parser: TypedArgumentParser[Config] = TypedArgumentParser(Config)
In the above line, passing the configuring NamedTuple
type to the constructor (on the right) lets the parser perform it's magic underneath
and return the parsed arguments as the specified type.
Type annotation of the parser (on the left) is not necessary, but it will allow IDEs such PyCharm
infer the type of the NamedTuple
returned by the parser.
If a type of a field in configuring NamedTuple
has been specified, i.e:
int_param: int
the TypedArgumentParser
will try to cast the argument with this field's name to that type and raise an error on failure.
Currently only Python's basic data types, i.e int
, float
and str
are supported.
If a field in the configuring NamedTuple
has a default value, this value becomes default value of the argument with this name.
If no default value has been specified, this argument is listed as non-optional.
TypedArgumentParser
attempts to parse the configuring NamedTuple
's docstring into a description of the script and it's arguments.
The docstring should follow Google convention.
Everything in the header of the docstring (before the Args
keyword) will be parsed into the script's description
(unless the description had been provided in the parser's constructor) and the descriptions of fields of the configuring NamedTuple
will be parsed into descriptions od the script's parameters.
pip install git+https://github.com/mprzewie/argtype
This library is highly type-oriented, so obviously Python 3.6+ is required.