Skip to main content

Extension for python argparse with typehints and typechecks.

Project description

typedparser

build 3.7 status build 3.9 status coverage version

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

  1. Create an attrs class (decorate with @attr.define)
  2. Define the fields with typedparser.add_argument - the syntax extends add_argument from argparse.
  3. 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


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)

Uploaded Source

Built Distribution

typedparser-0.1.19-py3-none-any.whl (11.2 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page