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.2.4.tar.gz
(11.7 kB
view hashes)
Built Distribution
Close
Hashes for typedparser-0.2.4-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c62d4c4f71cd12e04435d2bf093b0f3e9deb95762181d1659e66269826602be0 |
|
MD5 | e86b77f5445e5a364296cf5093895af9 |
|
BLAKE2b-256 | 70ab1d1e28bdf447561034302d6e73baebc3ccfcb229214c695f037f25eee486 |