argparser-adapter


Nameargparser-adapter JSON
Version 2.2.4 PyPI version JSON
download
home_pagehttps://github.com/NMRbox/argparser_adapter
SummaryAutomatically add object methods to argparser.
upload_time2023-06-22 12:17:44
maintainer
docs_urlNone
authorGerard
requires_python
licenseMIT license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            argparser_adapter
=================

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.

.. _type hints: https://docs.python.org/3/library/typing.html
.. _ValueError: https://docs.python.org/3/library/exceptions.html#ValueError
.. _Click: https://click.palletsprojects.com/


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/NMRbox/argparser_adapter",
    "name": "argparser-adapter",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Gerard",
    "author_email": "gweatherby@uchc.edu",
    "download_url": "https://files.pythonhosted.org/packages/11/0c/bcb6083a1a518d73729d517a9e8bd9cf165b6f2d759268b3fdadc80ab899/argparser_adapter-2.2.4.tar.gz",
    "platform": null,
    "description": "argparser_adapter\n=================\n\nThis package provides automatic adding of arguments to an argparser. ArgumentParser\nbased on a simple method naming convention.\n\nBasic Usage\n-----------\n\nWrite your class with methods you wish called from a command line decorated with *@CommandLine()*\nor *ChoiceCommand(choice)*\nCreate an **ArgparserAdapter**, passing your object as a constructor. Decorated methods\nwill be added to an argparser via the *register* call as positional or options. After parsing,\n*call_specified_methods* will call methods specified on command. ArgparseAdapter will\nattempt to convert command line strings to appropriate types if Python `type hints`_ are\nprovided.\n\nChoice Options\n--------------\nChoice options are added by first creating a *Choice* instance and then adding a *ChoiceCommand* decorator for\neach class method that should be a choice. The method name becomes a choice option for the specified choice. The\nmethod docstring becomes part of the the help.\n\nChoices may be positional or options, depending the value of the Choice *is_position* attribute. Default values\nmay be supplied.\n\nCommandLine Options\n~~~~~~~~~~~~~~~~~~~\nArguments may be designed as required using *@CommandLine(required=True).* Default values may\nbe specified with *@CommandLine(default=10).* Note specifying both required and a default is possible\nbut not useful.\n\nLogging\n~~~~~~~\nLogging is to: **logging.getLogger('argparser_adapter')**\n\nExample\n~~~~~~~\n\n::\n\n    import argparse\n    from ipaddress import IPv4Address\n\n    from argparser_adapter import CommandLine, ArgparserAdapter, Choice, ChoiceCommand\n\n    petchoice = Choice(\"pet\",False,default='cat',help=\"Pick your pet\")\n    funchoice = Choice(\"fun\",True,help=\"Pick your fun time\")\n\n\n    class Something:\n\n        @CommandLine()\n        def seven(self) -> int:\n            # no help for this argument\n            print(7)\n            return 7\n\n        @CommandLine()\n        def double(self, x: int):\n            \"\"\"double a number\"\"\"\n            print(2 * x)\n\n        @CommandLine()\n        def sum(self, x: int, y: int):\n            \"\"\"sum arguments\"\"\"\n            print(x + y)\n\n        @CommandLine(default=10)\n        def triple(self, x: int):\n            \"\"\"triple a value\"\"\"\n            print(3 * int(x))\n\n        @CommandLine()\n        def ipv4address(self, x: IPv4Address):\n            \"\"\"Print ip address\"\"\"\n            print(type(x))\n            print(x)\n\n        @CommandLine()\n        def hello(self):\n            print(\"Hi!\")\n\n        @CommandLine()\n        def binary(self, value: bool):\n            \"\"\"True or false\"\"\"\n            print(value)\n\n        @ChoiceCommand(funchoice)\n        def morning(self,name:str='Truman'):\n            \"\"\"The sun has risen\"\"\"\n            print(f\"morning {name}!\")\n\n        @ChoiceCommand(funchoice)\n        def night(self):\n            \"\"\"dark\"\"\"\n            print(\"it's dark\")\n\n        @ChoiceCommand(petchoice)\n        def dog(self):\n            \"\"\"canine\"\"\"\n            print(\"woof\")\n\n        @ChoiceCommand(petchoice)\n        def cat(self,name:str='Morris'):\n            \"\"\"feline\"\"\"\n            print(f\"meow {name}\")\n\n    def main():\n        something = Something()\n        adapter = ArgparserAdapter(something)\n        #parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)\n        adapter.register(parser)\n        args = parser.parse_args()\n        adapter.call_specified_methods(args)\n\n\n    if __name__ == \"__main__\":\n        main()\n\nNote the *double* will receive a string and must convert it to an integer. The\ntype hint in *triple* ensures the argument will be an integer.\n\nThe resulting argument argparser help is:\n\n::\n\n    usage: combined.py [-h] [--binary value] [--double x] [--hello]\n                       [--ipv4address x] [--seven] [--sum x y] [--triple x]\n                       [--pet {cat,dog}]\n                       {morning,night}\n\n    positional arguments:\n      {morning,night}  Pick your fun time\n                       morning (The sun has risen)\n                       night (dark)\n\n    optional arguments:\n      -h, --help       show this help message and exit\n      --binary value   True or false\n      --double x       double a number\n      --hello\n      --ipv4address x  Print ip address\n      --seven\n      --sum x y        sum arguments\n      --triple x       triple a value\n      --pet {cat,dog}  Pick your pet\n                       cat (feline)\n                       dog (canine)\n\nDocstrings, if present, become help arguments.\n\nAdvanced usage\n______________\nWhen type conversion fails, the method\n\n::\n\n    def param_conversion_exception(self, e: Exception, method_name: str, parameter_name: str, parameter_type: type,\n                                   value: str) -> Any:\n\nis called. The default behavior is to raise a ValueError_ exception including the method and parameter names, the value\npassed and the original exception message. This method is provided for subclasses to override,\nif desired. An implementation should raise an Exception or return a suitable parameter for\ncalling *method_name*.\n\nAlternative packages\n--------------------\nMore complete packages are available for this purpose, such as Click_. This implementation is\nintended to be simple, lightweight and easy to use.\n\n.. _type hints: https://docs.python.org/3/library/typing.html\n.. _ValueError: https://docs.python.org/3/library/exceptions.html#ValueError\n.. _Click: https://click.palletsprojects.com/\n\n",
    "bugtrack_url": null,
    "license": "MIT license",
    "summary": "Automatically add object methods to argparser.",
    "version": "2.2.4",
    "project_urls": {
        "Homepage": "https://github.com/NMRbox/argparser_adapter"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2076bd18669b43394e9502ca9efcbe8776573939af7ac47703a22ca5179eb9ef",
                "md5": "50df6ad60f704b357add7796cbf8d145",
                "sha256": "f5e79cf64043021358eaa2d93ecb07177960c2d3a1aa2e52b1bcb678d2d47bbc"
            },
            "downloads": -1,
            "filename": "argparser_adapter-2.2.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "50df6ad60f704b357add7796cbf8d145",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 6947,
            "upload_time": "2023-06-22T12:17:42",
            "upload_time_iso_8601": "2023-06-22T12:17:42.875898Z",
            "url": "https://files.pythonhosted.org/packages/20/76/bd18669b43394e9502ca9efcbe8776573939af7ac47703a22ca5179eb9ef/argparser_adapter-2.2.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "110cbcb6083a1a518d73729d517a9e8bd9cf165b6f2d759268b3fdadc80ab899",
                "md5": "a0d330434079ecc415cd3724986884a5",
                "sha256": "f81f690c94bd21d6558a7b3f8498ff920285c1d74421922fa3c676ce1af9edd5"
            },
            "downloads": -1,
            "filename": "argparser_adapter-2.2.4.tar.gz",
            "has_sig": false,
            "md5_digest": "a0d330434079ecc415cd3724986884a5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 6536,
            "upload_time": "2023-06-22T12:17:44",
            "upload_time_iso_8601": "2023-06-22T12:17:44.326182Z",
            "url": "https://files.pythonhosted.org/packages/11/0c/bcb6083a1a518d73729d517a9e8bd9cf165b6f2d759268b3fdadc80ab899/argparser_adapter-2.2.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-22 12:17:44",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "NMRbox",
    "github_project": "argparser_adapter",
    "github_not_found": true,
    "lcname": "argparser-adapter"
}
        
Elapsed time: 0.08291s