Skip to main content

This package provides automatic adding of arguments to an argparser. ArgumentParser based on a simple method naming convention.

Basic Usage

Write your class with methods you wish called from a command line decorated with @CommandLine() or ChoiceCommand(choice) Create an ArgparserAdapter, passing your object as a constructor. Decorated methods will be added to an argparser via the register call as positional or options. After parsing, call_specified_methods will call methods specified on command. ArgparseAdapter will attempt to convert command line strings to appropriate types if Python type hints are provided.

Choice Options

Choice options are added by first creating a Choice instance and then adding a ChoiceCommand decorator for each class method that should be a choice. The method name becomes a choice option for the specified choice. The method docstring becomes part of the the help.

Choices may be positional or options, depending the value of the Choice is_position attribute. Default values may be supplied.

CommandLine Options

Arguments may be designed as required using @CommandLine(required=True). Default values may be specified with @CommandLine(default=10). Note specifying both required and a default is possible but not useful.

Logging

Logging is to: logging.getLogger(‘argparser_adapter’)

Example

import argparse
from ipaddress import IPv4Address

from argparser_adapter import CommandLine, ArgparserAdapter, Choice, ChoiceCommand

petchoice = Choice("pet",False,default='cat',help="Pick your pet")
funchoice = Choice("fun",True,help="Pick your fun time")


class Something:

    @CommandLine()
    def seven(self) -> int:
        # no help for this argument
        print(7)
        return 7

    @CommandLine()
    def double(self, x: int):
        """double a number"""
        print(2 * x)

    @CommandLine()
    def sum(self, x: int, y: int):
        """sum arguments"""
        print(x + y)

    @CommandLine(default=10)
    def triple(self, x: int):
        """triple a value"""
        print(3 * int(x))

    @CommandLine()
    def ipv4address(self, x: IPv4Address):
        """Print ip address"""
        print(type(x))
        print(x)

    @CommandLine()
    def hello(self):
        print("Hi!")

    @CommandLine()
    def binary(self, value: bool):
        """True or false"""
        print(value)

    @ChoiceCommand(funchoice)
    def morning(self,name:str='Truman'):
        """The sun has risen"""
        print(f"morning {name}!")

    @ChoiceCommand(funchoice)
    def night(self):
        """dark"""
        print("it's dark")

    @ChoiceCommand(petchoice)
    def dog(self):
        """canine"""
        print("woof")

    @ChoiceCommand(petchoice)
    def cat(self,name:str='Morris'):
        """feline"""
        print(f"meow {name}")

def main():
    something = Something()
    adapter = ArgparserAdapter(something)
    #parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
    adapter.register(parser)
    args = parser.parse_args()
    adapter.call_specified_methods(args)


if __name__ == "__main__":
    main()

Note the double will receive a string and must convert it to an integer. The type hint in triple ensures the argument will be an integer.

The resulting argument argparser help is:

usage: combined.py [-h] [--binary value] [--double x] [--hello]
                   [--ipv4address x] [--seven] [--sum x y] [--triple x]
                   [--pet {cat,dog}]
                   {morning,night}

positional arguments:
  {morning,night}  Pick your fun time
                   morning (The sun has risen)
                   night (dark)

optional arguments:
  -h, --help       show this help message and exit
  --binary value   True or false
  --double x       double a number
  --hello
  --ipv4address x  Print ip address
  --seven
  --sum x y        sum arguments
  --triple x       triple a value
  --pet {cat,dog}  Pick your pet
                   cat (feline)
                   dog (canine)

Docstrings, if present, become help arguments.

Advanced usage

When type conversion fails, the method

def param_conversion_exception(self, e: Exception, method_name: str, parameter_name: str, parameter_type: type,
                               value: str) -> Any:

is called. The default behavior is to raise a ValueError exception including the method and parameter names, the value passed and the original exception message. This method is provided for subclasses to override, if desired. An implementation should raise an Exception or return a suitable parameter for calling method_name.

Alternative packages

More complete packages are available for this purpose, such as Click. This implementation is intended to be simple, lightweight and easy to use.

Metadata

Release files for argparser-adapter 2.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for argparser-adapter 2.2.4
File Size Uploaded
argparser_adapter-2.2.4.tar.gz 6.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for argparser-adapter 2.2.4
File Interpreter ABI Platform
argparser_adapter-2.2.4-py3-none-any.whl Python 3 none any Details

Total release size: 13.5 kB

Release files / argparser_adapter-2.2.4.tar.gz

Download URL argparser_adapter-2.2.4.tar.gz
Size 6.5 kB
Tags Source
SHA-256 checksum
How to use checksums
f81f690c94bd21d6558a7b3f8498ff920285c1d74421922fa3c676ce1af9edd5
BLAKE2b-256 checksum
How to use checksums
110cbcb6083a1a518d73729d517a9e8bd9cf165b6f2d759268b3fdadc80ab899
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.4.2 requests/2.22.0 setuptools/65.6.3 requests-toolbelt/0.8.0 tqdm/4.64.1 CPython/3.8.10

Release files / argparser_adapter-2.2.4-py3-none-any.whl

Download URL argparser_adapter-2.2.4-py3-none-any.whl
Size 6.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f5e79cf64043021358eaa2d93ecb07177960c2d3a1aa2e52b1bcb678d2d47bbc
BLAKE2b-256 checksum
How to use checksums
2076bd18669b43394e9502ca9efcbe8776573939af7ac47703a22ca5179eb9ef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.4.2 requests/2.22.0 setuptools/65.6.3 requests-toolbelt/0.8.0 tqdm/4.64.1 CPython/3.8.10

Release history Release notifications | RSS feed

This release

2.2.4 This release

2 release files

2.2.3

2 release files

2.2.2

2 release files

2.2.1

2 release files

2.2

2 release files

2.1

2 release files

2.0

1 release file

1.4.1

1 release file

1.4

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page