Skip to main content

A simple but handy Python library to generate a `argparse.ArgumentParser` object from a type-annotated method

Project description

with-argparse

with-argparse is a very simple and tiny package using argparse.ArgumentParser objects to derive a CLI that is automatically applied to a function using type annotations. Currently supports Python 3.10-11.

Supported features:

  • Argument lists via nargs=+
  • Argument choices via typing.Literal[x, y, z]
  • Optional values and required arguments
  • Boolean flags via presence or abscence of --argument_name
  • Custom parse functions via @with_argparse(arg_name=custom_fn)
  • Ignored values: @with_argparse(ignore_keys={'arg_name'}
  • Nested type annotations such as list[int]
  • Disabled mode: with_argparse.no_argparse() context manager

In order for this package to work, functions must receive an explicit type annotation. The following type annotations are currently supported:

  • str, int, float, bool, ...
  • Types that have constructors that accept a single str as input
  • list[type] and set[type]
  • Optional[type], type | None, Union[type, None],
  • Literal[type_val1, type_val2]
  • Custom types via custom parse functions (supplied via kwarg to the @with_argparse decorator.

Example code

from typing import Optional
from with_argparse import with_argparse

def custom_parse_fn(inp: str) -> int:
    return 42 if inp == "yeah" else -1

@with_argparse(
    ignore_keys={"ignored_value"}, 
    complex_input=custom_parse_fn
)
def cli(
    theory_of_everything: int,
    complex_input: int,
    ignored_value: Optional[str] = None,
) -> int:
    print(ignored_value)
    return theory_of_everything * complex_input

cli(ignored_value="abc")

will generate the following CLI output when run:

usage: --theory_of_everything THEORY_OF_EVERYTHING
                    [--complex_input COMPLEX_INPUT]

Custom parse functions

Becomes increasingly useful when the target type T does not have a default constructor with a single str argument or more complex logic is required to parse the desired type from a string input.

As it is not type correct to use functions as type annotations (it would work extracting those functions from there, however type checkers such as mypy will complain when doing so), one can specify custom parse functions directly in the @with_argparse() decorator via a keyword argument named as the target parameter.

Say we have a complex function that does call some other functions before eventually returning the string in reverse:

def func_a(a: str) -> str: ...
def func_b(b: str) -> str: ...

def custom_fn(inp: str):
    inp = func_a(inp)
    inp = func_b(inp)
    return str(reversed(inp))

Our custom function can also accept types differing from str, such as int.

We can then use this function to parse the input the following way in our dummy cli function:

@with_argparse(complex_input=custom_fn)
def cli(complex_input: str) -> str:
    return complex_input

Boolean values

For Boolean values, if the default specified is True, the CLI argument name is renamed to --no_argname, such that the user must specify to disable the given argument. In any other case (None, False), the user must specify --arg_name to set the Boolean argument to True,

The renaming of a parameter can be disabled by specifying its name in the set ignore_mapping, again in the @with_argparse decorator to the function.

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

with_argparse-1.0.5rc4.tar.gz (17.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

with_argparse-1.0.5rc4-py3-none-any.whl (15.9 kB view details)

Uploaded Python 3

File details

Details for the file with_argparse-1.0.5rc4.tar.gz.

File metadata

  • Download URL: with_argparse-1.0.5rc4.tar.gz
  • Upload date:
  • Size: 17.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for with_argparse-1.0.5rc4.tar.gz
Algorithm Hash digest
SHA256 9d3f53f82fd4dbcea2faaf564b0ec79f1b7bfa698053a22da8c7dc3de5cc49a3
MD5 41331652aef58a40141fe9b82b616540
BLAKE2b-256 b945882ae3d2e7cf949a61eb09c9f54cce8bb968cbc99c6bfd0b60865aa65a29

See more details on using hashes here.

File details

Details for the file with_argparse-1.0.5rc4-py3-none-any.whl.

File metadata

File hashes

Hashes for with_argparse-1.0.5rc4-py3-none-any.whl
Algorithm Hash digest
SHA256 2b9e9712f2643c4ded4a244dd7f0f1d2a1486b7da18d4f136b71b07e6be2a257
MD5 890175f70f36090958e797d81bb750f7
BLAKE2b-256 385792e2f85bbe0dc6944f8eb4cf7a6fa978800e79b5a535d6e7f9c55009b948

See more details on using hashes here.

Supported by

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