Extension for python argparse with typehints and typechecks.
Project description
typedparser
Typing extension for python argparse using attrs and typedattr.
Why use this library? It allows creating arguments with type hints and checks while staying very close to the syntax of the standard library's argparse.
Install
Requires python>=3.7
pip install typedparser
Usage
- Create an attrs class (decorate with
@attr.define
) - Define the fields with
typedparser.add_argument
- the syntax extends add_argument from argparse. - Parse the args with
TypedParser
, now the args are typechecked and there are typehints available.
from typing import Optional
from attrs import define
from typedparser import add_argument, TypedParser
@define
class Args:
foo: int = add_argument("foo", type=int)
bar: int = add_argument("-b", "--bar", type=int, default=0)
# Syntax extensions:
# Omit argument name to create an optional argument --opt
opt: Optional[int] = add_argument(type=int)
# Use shortcut to create an optional argument -s / --short
short: Optional[int] = add_argument(shortcut="-s", type=int)
def main():
parser = TypedParser.create_parser(Args)
args: Args = parser.parse_args()
print(args)
if __name__ == "__main__":
main()
Advanced usage
- Use
TypedParser.from_parser(parser, Args)
to add typing to an existing parser. This is useful to cover usecases like subparsers or argument groups.
Install locally and run tests
Clone repository and cd into, then:
pip install -e .
pip install pytest pytest-cov pylint pytest-lazy-fixture
pylint typedparser
# run tests for python>=3.7
python -m pytest --cov
pylint tests
# run tests for python>=3.9
python -m pytest tests tests_py39 --cov
pylint tests
pylint tests_py39
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
typedparser-0.1.19.tar.gz
(11.7 kB
view hashes)
Built Distribution
Close
Hashes for typedparser-0.1.19-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1c3e6f5d5e4d4059bf4266a066040c988757c3a9525fbafeeb0d7fc926b62c0a |
|
MD5 | 40aefa288f8d9905d2138213815ca49a |
|
BLAKE2b-256 | fa26bc66705190b85534fca4d954103bc9d3bcc98c85805bf44e45518362778c |