classparse


Nameclassparse JSON
Version 0.1.4 PyPI version JSON
download
home_page
SummaryDeclarative `ArgumentParser` definition with `dataclass` notation.
upload_time2023-05-24 06:17:56
maintainer
docs_urlNone
author
requires_python>=3.8
licenseBSD-3-Clause
keywords argparse dataclass
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <!---
Copyright (c) 2023-2023, Liran Funaro.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
--->

# classparse

[![Coverage Status](https://coveralls.io/repos/github/liran-funaro/classparse/badge.svg?branch=main)](https://coveralls.io/github/liran-funaro/classparse?branch=main)

Declarative `ArgumentParser` definition with `dataclass` notation.
 - No `ArgumentParser` boilerplate code
 - IDE autocompletion and type hints

# Install
```bash
pip install classparse==0.1.4
```

# Simple Example
This is a simple example of the most basic usage of this library.
<!-- embed: examples/simple.py -->

```python
# examples/simple.py
from dataclasses import dataclass

from classparse import classparser

@classparser
@dataclass
class SimpleArgs:
    """My simple program's arguments"""

    retries: int = 5  # number of retries
    eps: float = 1e-3  # epsilon

if __name__ == "__main__":
    print(SimpleArgs.parse_args())
```

<!-- execute: python examples/simple.py --help -->
```bash
$ python examples/simple.py --help
usage: simple.py [-h] [--retries RETRIES] [--eps EPS]

My simple program's arguments

options:
  -h, --help         show this help message and exit
  --retries RETRIES  number of retries
  --eps EPS          epsilon
```

<!-- execute: python examples/simple.py --retries 10 --eps 1e-6 -->
```text
$ python examples/simple.py --retries 10 --eps 1e-6
SimpleArgs(retries=10, eps=1e-06)
```

# Exhaustive Usage Example
This example demonstrates all the usage scenarios of this library.
<!-- embed: examples/usage.py -->

```python
# examples/usage.py
import dataclasses
from dataclasses import dataclass
from enum import Enum, auto
from pathlib import Path
from typing import List, Literal, Optional, Tuple, Union

from classparse import arg, classparser, no_arg, pos_arg, to_arg_name, to_var_name

class Action(Enum):
    Initialize = "init"
    Execute = "exec"

class Animal(Enum):
    Cat = auto()
    Dog = auto()

@classparser(
    prog="my_program.py",  # Keyword arguments are passed to the parser init.
    default_argument_args=dict(help="(type: %(type)s)"),  # Set default arguments for each call of add_argument().
)
@dataclass(frozen=True)
class AllOptions:
    """
    Class doc string ==> parser description.
    The fields' inline/above comment ==> argument's help.
    """

    pos_arg_1: str  # Field with no explicit default ==> positional arguments (default=%(default)s)
    pos_arg_2: int = pos_arg(
        5,
        nargs="?",
        help=(
            "pos_arg() is a wrapper around dataclasses.field()."
            "The first argument (optional) is the argument default (default=%(default)s)."
            "The following keyword arguments can be any argparse.add_argument() parameter."
        ),
    )  # When the help field is specified explicitly, the inline comment is ignored
    int_arg: int = 1  # Field's type and default are applied to the parser (type=%(type)s, default=%(default)s)
    str_enum_choice_arg: Action = Action.Initialize  # StrEnum ==> choice argument (type=%(type)s, default=%(default)s)
    int_enum_choice_arg: Animal = Animal.Cat  # IntEnum ==> choice argument (type=%(type)s, default=%(default)s)
    literal_arg: Literal["a", "b", "c"] = None  # Literal ==> choice argument (type=%(type)s, default=%(default)s)
    literal_int_arg: Literal[1, 2, 3] = None  # Literal's type is automatically inferred (type=%(type)s)
    mixed_literal: Literal[1, 2, "3", "4", True, Animal.Cat] = None  # We can mix multiple literal types (type=%(type)s)
    optional_arg: Optional[int] = None  # Optional can be used for type hinting (type=%(type)s)
    just_optional_arg: Optional = None  # Bare optional also works (type=%(type)s)
    optional_choice_arg: Optional[Action] = None  # Nested types are supported (type=%(type)s)
    union_arg: Union[int, float, bool] = None  # Tries to convert to type in order until first success (type=%(type)s)
    path_arg: Path = None
    flag_arg: int = arg(
        "-f",
        help=(
            "arg() is a wrapper around dataclasses.field()."
            "The first argument (optional) is the short argument name."
            "The following keyword arguments can be any argparse.add_argument() parameter."
        ),
        default=1,
    )
    required_arg: float = arg("-r", required=True)  # E.g., required=%(required)s
    metavar_arg: str = arg(metavar="M")  # E.g., metavar=%(metavar)s
    int_list: List[int] = (1,)  # List type hint ==> nargs="+" (type=%(type)s)
    int_2_list: Tuple[int, int] = (1, 2)  # Tuple type hint ==> nargs=<tuple length> (nargs=%(nargs)s, type=%(type)s)
    multi_type_tuple: Tuple[int, float, str] = (1, 1e-3, "a")  # We can use multiple types (type=%(type)s)
    actions: List[Action] = ()  # List[Enum] ==> choices with nargs="+" (nargs=%(nargs)s, type=%(type)s)
    animals: List[Animal] = ()  # List[Enum] ==> choices with nargs="+" (nargs=%(nargs)s, type=%(type)s)
    literal_list: List[Literal["aa", "bb", 11, 22, Animal.Cat]] = ("aa",)  # List[Literal] ==> choices with nargs="+"
    union_list: List[Union[int, float, str, bool]] = ()
    union_with_literal: List[Union[Literal["a", "b", 1, 2], float, bool]] = ()
    typeless_list: list = ()  # If list type is unspecified, then it uses argparse default (type=%(type)s)
    typeless_typing_list: List = ()  # typing.List or list are supported
    none_bool_arg: bool = None  # boolean args ==> argparse.BooleanOptionalAction (type=%(type)s)
    true_bool_arg: bool = True  # We can set any default value
    false_bool_arg: bool = False
    complex_arg: complex = complex(1, -1)

    # no_arg() is used to not include this argument in the parser.
    # The first argument (optional) sets the default value.
    # The following keyword arguments is forwarded to the dataclasses.field() method.
    no_arg: int = no_arg(0)

    # We used this argument for the README example.
    # Note that comments above the arg are also included in the help of the argument.
    # This is a convenient way to include long help messages.
    show: List[str] = arg("-s", default=())

    def __repr__(self):
        """Print only the specified fields"""
        fields = self.show or list(dataclasses.asdict(self))
        return "\n".join([f"{to_arg_name(k)}: {getattr(self, to_var_name(k))}" for k in fields])

if __name__ == "__main__":
    print(AllOptions.parse_args())
```

<!-- execute: python examples/usage.py --help -->
```text
$ python examples/usage.py --help
usage: my_program.py [-h] [--int-arg INT_ARG]
                     [--str-enum-choice-arg {Initialize/init,Execute/exec}]
                     [--int-enum-choice-arg {Cat/1,Dog/2}]
                     [--literal-arg {a,b,c}] [--literal-int-arg {1,2,3}]
                     [--mixed-literal {1,2,3,4,True,Cat/1}]
                     [--optional-arg OPTIONAL_ARG]
                     [--just-optional-arg JUST_OPTIONAL_ARG]
                     [--optional-choice-arg {Initialize/init,Execute/exec}]
                     [--union-arg UNION_ARG] [--path-arg PATH_ARG]
                     [-f FLAG_ARG] -r REQUIRED_ARG [--metavar-arg M]
                     [--int-list INT_LIST [INT_LIST ...]]
                     [--int-2-list INT_2_LIST INT_2_LIST]
                     [--multi-type-tuple MULTI_TYPE_TUPLE MULTI_TYPE_TUPLE MULTI_TYPE_TUPLE]
                     [--actions {Initialize/init,Execute/exec} [{Initialize/init,Execute/exec} ...]]
                     [--animals {Cat/1,Dog/2} [{Cat/1,Dog/2} ...]]
                     [--literal-list {aa,bb,11,22,Cat/1} [{aa,bb,11,22,Cat/1} ...]]
                     [--union-list UNION_LIST [UNION_LIST ...]]
                     [--union-with-literal UNION_WITH_LITERAL [UNION_WITH_LITERAL ...]]
                     [--typeless-list TYPELESS_LIST [TYPELESS_LIST ...]]
                     [--typeless-typing-list TYPELESS_TYPING_LIST [TYPELESS_TYPING_LIST ...]]
                     [--none-bool-arg | --no-none-bool-arg]
                     [--true-bool-arg | --no-true-bool-arg]
                     [--false-bool-arg | --no-false-bool-arg]
                     [--complex-arg COMPLEX_ARG] [-s SHOW [SHOW ...]]
                     pos-arg-1 [pos-arg-2]

Class doc string ==> parser description. The fields' inline/above comment ==>
argument's help.

positional arguments:
  pos-arg-1             Field with no explicit default ==> positional
                        arguments (default=None)
  pos-arg-2             pos_arg() is a wrapper around dataclasses.field().The
                        first argument (optional) is the argument default
                        (default=5).The following keyword arguments can be any
                        argparse.add_argument() parameter.

options:
  -h, --help            show this help message and exit
  --int-arg INT_ARG     Field's type and default are applied to the parser
                        (type=int, default=1)
  --str-enum-choice-arg {Initialize/init,Execute/exec}
                        StrEnum ==> choice argument (type=Action,
                        default=Initialize)
  --int-enum-choice-arg {Cat/1,Dog/2}
                        IntEnum ==> choice argument (type=Animal, default=Cat)
  --literal-arg {a,b,c}
                        Literal ==> choice argument (type=str, default=None)
  --literal-int-arg {1,2,3}
                        Literal's type is automatically inferred (type=int)
  --mixed-literal {1,2,3,4,True,Cat/1}
                        We can mix multiple literal types
                        (type=typing.Literal[1, 2, '3', '4', True,
                        <Animal.Cat: 1>])
  --optional-arg OPTIONAL_ARG
                        Optional can be used for type hinting (type=int)
  --just-optional-arg JUST_OPTIONAL_ARG
                        Bare optional also works (type=None)
  --optional-choice-arg {Initialize/init,Execute/exec}
                        Nested types are supported (type=Action)
  --union-arg UNION_ARG
                        Tries to convert to type in order until first success
                        (type=typing.Union[int, float, bool])
  --path-arg PATH_ARG   (type: Path)
  -f FLAG_ARG, --flag-arg FLAG_ARG
                        arg() is a wrapper around dataclasses.field().The
                        first argument (optional) is the short argument
                        name.The following keyword arguments can be any
                        argparse.add_argument() parameter.
  -r REQUIRED_ARG, --required-arg REQUIRED_ARG
                        E.g., required=True
  --metavar-arg M       E.g., metavar=M
  --int-list INT_LIST [INT_LIST ...]
                        List type hint ==> nargs="+" (type=int)
  --int-2-list INT_2_LIST INT_2_LIST
                        Tuple type hint ==> nargs=<tuple length> (nargs=2,
                        type=int)
  --multi-type-tuple MULTI_TYPE_TUPLE MULTI_TYPE_TUPLE MULTI_TYPE_TUPLE
                        We can use multiple types (type=typing.Union[int,
                        float, str])
  --actions {Initialize/init,Execute/exec} [{Initialize/init,Execute/exec} ...]
                        List[Enum] ==> choices with nargs="+" (nargs=+,
                        type=Action)
  --animals {Cat/1,Dog/2} [{Cat/1,Dog/2} ...]
                        List[Enum] ==> choices with nargs="+" (nargs=+,
                        type=Animal)
  --literal-list {aa,bb,11,22,Cat/1} [{aa,bb,11,22,Cat/1} ...]
                        List[Literal] ==> choices with nargs="+"
  --union-list UNION_LIST [UNION_LIST ...]
                        (type: typing.Union[int, float, str, bool])
  --union-with-literal UNION_WITH_LITERAL [UNION_WITH_LITERAL ...]
                        (type: typing.Union[typing.Literal['a', 'b', 1, 2],
                        float, bool])
  --typeless-list TYPELESS_LIST [TYPELESS_LIST ...]
                        If list type is unspecified, then it uses argparse
                        default (type=None)
  --typeless-typing-list TYPELESS_TYPING_LIST [TYPELESS_TYPING_LIST ...]
                        typing.List or list are supported
  --none-bool-arg, --no-none-bool-arg
                        boolean args ==> argparse.BooleanOptionalAction
                        (type=bool)
  --true-bool-arg, --no-true-bool-arg
                        We can set any default value (default: True)
  --false-bool-arg, --no-false-bool-arg
                        (type: bool) (default: False)
  --complex-arg COMPLEX_ARG
                        (type: complex)
  -s SHOW [SHOW ...], --show SHOW [SHOW ...]
                        We used this argument for the README example. Note
                        that comments above the arg are also included in the
                        help of the argument. This is a convenient way to
                        include long help messages.
```

Note that for Enums, we can use either the enum name or its value.
<!-- execute: python examples/usage.py str-choices --actions Initialize init Execute exec -r1 -s actions -->
```text
$ python examples/usage.py str-choices --actions Initialize init Execute exec -r1 -s actions
actions: [<Action.Initialize: 'init'>, <Action.Initialize: 'init'>, <Action.Execute: 'exec'>, <Action.Execute: 'exec'>]
```
<!-- execute: python examples/usage.py int-choices --animals Cat 1 Dog 2 -r1 -s animals -->
```text
$ python examples/usage.py int-choices --animals Cat 1 Dog 2 -r1 -s animals
animals: [<Animal.Cat: 1>, <Animal.Cat: 1>, <Animal.Dog: 2>, <Animal.Dog: 2>]
```

# Alternatives

#### [mivade/argparse_dataclass](https://github.com/mivade/argparse_dataclass)
  - Allow transforming dataclass to `ArgumentParser`.
  - Missing features:
    - `Enum` support
    - `arg/pos_arg/no_arg` functionality
    - Implicit positional argument
    - `nargs` support

#### [lebrice/simple-parsing](https://github.com/lebrice/SimpleParsing)
  - Allow adding dataclass to `ArgumentParser` by using `parser.add_arguments()`
  - Requires boilerplate code to create the parser
  - Positional arguments
  - `nargs` support

### [swansonk14/typed-argument-parser](https://github.com/swansonk14/typed-argument-parser)
  - Creating argument parser from classes and functions
  - Rich functionality
  - Post-processing of arguments
  - Save/load arguments
  - Load from dict

# License

[BSD-3](LICENSE)

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "classparse",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "argparse,dataclass",
    "author": "",
    "author_email": "Liran Funaro <liran.funaro@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/d3/37/cce3269c3d65569f962fbabc3bfe5d678fcd0daa43b788220dae910cb930/classparse-0.1.4.tar.gz",
    "platform": null,
    "description": "<!---\nCopyright (c) 2023-2023, Liran Funaro.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n3. Neither the name of the copyright holder nor the\n   names of its contributors may be used to endorse or promote products\n   derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n--->\n\n# classparse\n\n[![Coverage Status](https://coveralls.io/repos/github/liran-funaro/classparse/badge.svg?branch=main)](https://coveralls.io/github/liran-funaro/classparse?branch=main)\n\nDeclarative `ArgumentParser` definition with `dataclass` notation.\n - No `ArgumentParser` boilerplate code\n - IDE autocompletion and type hints\n\n# Install\n```bash\npip install classparse==0.1.4\n```\n\n# Simple Example\nThis is a simple example of the most basic usage of this library.\n<!-- embed: examples/simple.py -->\n\n```python\n# examples/simple.py\nfrom dataclasses import dataclass\n\nfrom classparse import classparser\n\n@classparser\n@dataclass\nclass SimpleArgs:\n    \"\"\"My simple program's arguments\"\"\"\n\n    retries: int = 5  # number of retries\n    eps: float = 1e-3  # epsilon\n\nif __name__ == \"__main__\":\n    print(SimpleArgs.parse_args())\n```\n\n<!-- execute: python examples/simple.py --help -->\n```bash\n$ python examples/simple.py --help\nusage: simple.py [-h] [--retries RETRIES] [--eps EPS]\n\nMy simple program's arguments\n\noptions:\n  -h, --help         show this help message and exit\n  --retries RETRIES  number of retries\n  --eps EPS          epsilon\n```\n\n<!-- execute: python examples/simple.py --retries 10 --eps 1e-6 -->\n```text\n$ python examples/simple.py --retries 10 --eps 1e-6\nSimpleArgs(retries=10, eps=1e-06)\n```\n\n# Exhaustive Usage Example\nThis example demonstrates all the usage scenarios of this library.\n<!-- embed: examples/usage.py -->\n\n```python\n# examples/usage.py\nimport dataclasses\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\nfrom pathlib import Path\nfrom typing import List, Literal, Optional, Tuple, Union\n\nfrom classparse import arg, classparser, no_arg, pos_arg, to_arg_name, to_var_name\n\nclass Action(Enum):\n    Initialize = \"init\"\n    Execute = \"exec\"\n\nclass Animal(Enum):\n    Cat = auto()\n    Dog = auto()\n\n@classparser(\n    prog=\"my_program.py\",  # Keyword arguments are passed to the parser init.\n    default_argument_args=dict(help=\"(type: %(type)s)\"),  # Set default arguments for each call of add_argument().\n)\n@dataclass(frozen=True)\nclass AllOptions:\n    \"\"\"\n    Class doc string ==> parser description.\n    The fields' inline/above comment ==> argument's help.\n    \"\"\"\n\n    pos_arg_1: str  # Field with no explicit default ==> positional arguments (default=%(default)s)\n    pos_arg_2: int = pos_arg(\n        5,\n        nargs=\"?\",\n        help=(\n            \"pos_arg() is a wrapper around dataclasses.field().\"\n            \"The first argument (optional) is the argument default (default=%(default)s).\"\n            \"The following keyword arguments can be any argparse.add_argument() parameter.\"\n        ),\n    )  # When the help field is specified explicitly, the inline comment is ignored\n    int_arg: int = 1  # Field's type and default are applied to the parser (type=%(type)s, default=%(default)s)\n    str_enum_choice_arg: Action = Action.Initialize  # StrEnum ==> choice argument (type=%(type)s, default=%(default)s)\n    int_enum_choice_arg: Animal = Animal.Cat  # IntEnum ==> choice argument (type=%(type)s, default=%(default)s)\n    literal_arg: Literal[\"a\", \"b\", \"c\"] = None  # Literal ==> choice argument (type=%(type)s, default=%(default)s)\n    literal_int_arg: Literal[1, 2, 3] = None  # Literal's type is automatically inferred (type=%(type)s)\n    mixed_literal: Literal[1, 2, \"3\", \"4\", True, Animal.Cat] = None  # We can mix multiple literal types (type=%(type)s)\n    optional_arg: Optional[int] = None  # Optional can be used for type hinting (type=%(type)s)\n    just_optional_arg: Optional = None  # Bare optional also works (type=%(type)s)\n    optional_choice_arg: Optional[Action] = None  # Nested types are supported (type=%(type)s)\n    union_arg: Union[int, float, bool] = None  # Tries to convert to type in order until first success (type=%(type)s)\n    path_arg: Path = None\n    flag_arg: int = arg(\n        \"-f\",\n        help=(\n            \"arg() is a wrapper around dataclasses.field().\"\n            \"The first argument (optional) is the short argument name.\"\n            \"The following keyword arguments can be any argparse.add_argument() parameter.\"\n        ),\n        default=1,\n    )\n    required_arg: float = arg(\"-r\", required=True)  # E.g., required=%(required)s\n    metavar_arg: str = arg(metavar=\"M\")  # E.g., metavar=%(metavar)s\n    int_list: List[int] = (1,)  # List type hint ==> nargs=\"+\" (type=%(type)s)\n    int_2_list: Tuple[int, int] = (1, 2)  # Tuple type hint ==> nargs=<tuple length> (nargs=%(nargs)s, type=%(type)s)\n    multi_type_tuple: Tuple[int, float, str] = (1, 1e-3, \"a\")  # We can use multiple types (type=%(type)s)\n    actions: List[Action] = ()  # List[Enum] ==> choices with nargs=\"+\" (nargs=%(nargs)s, type=%(type)s)\n    animals: List[Animal] = ()  # List[Enum] ==> choices with nargs=\"+\" (nargs=%(nargs)s, type=%(type)s)\n    literal_list: List[Literal[\"aa\", \"bb\", 11, 22, Animal.Cat]] = (\"aa\",)  # List[Literal] ==> choices with nargs=\"+\"\n    union_list: List[Union[int, float, str, bool]] = ()\n    union_with_literal: List[Union[Literal[\"a\", \"b\", 1, 2], float, bool]] = ()\n    typeless_list: list = ()  # If list type is unspecified, then it uses argparse default (type=%(type)s)\n    typeless_typing_list: List = ()  # typing.List or list are supported\n    none_bool_arg: bool = None  # boolean args ==> argparse.BooleanOptionalAction (type=%(type)s)\n    true_bool_arg: bool = True  # We can set any default value\n    false_bool_arg: bool = False\n    complex_arg: complex = complex(1, -1)\n\n    # no_arg() is used to not include this argument in the parser.\n    # The first argument (optional) sets the default value.\n    # The following keyword arguments is forwarded to the dataclasses.field() method.\n    no_arg: int = no_arg(0)\n\n    # We used this argument for the README example.\n    # Note that comments above the arg are also included in the help of the argument.\n    # This is a convenient way to include long help messages.\n    show: List[str] = arg(\"-s\", default=())\n\n    def __repr__(self):\n        \"\"\"Print only the specified fields\"\"\"\n        fields = self.show or list(dataclasses.asdict(self))\n        return \"\\n\".join([f\"{to_arg_name(k)}: {getattr(self, to_var_name(k))}\" for k in fields])\n\nif __name__ == \"__main__\":\n    print(AllOptions.parse_args())\n```\n\n<!-- execute: python examples/usage.py --help -->\n```text\n$ python examples/usage.py --help\nusage: my_program.py [-h] [--int-arg INT_ARG]\n                     [--str-enum-choice-arg {Initialize/init,Execute/exec}]\n                     [--int-enum-choice-arg {Cat/1,Dog/2}]\n                     [--literal-arg {a,b,c}] [--literal-int-arg {1,2,3}]\n                     [--mixed-literal {1,2,3,4,True,Cat/1}]\n                     [--optional-arg OPTIONAL_ARG]\n                     [--just-optional-arg JUST_OPTIONAL_ARG]\n                     [--optional-choice-arg {Initialize/init,Execute/exec}]\n                     [--union-arg UNION_ARG] [--path-arg PATH_ARG]\n                     [-f FLAG_ARG] -r REQUIRED_ARG [--metavar-arg M]\n                     [--int-list INT_LIST [INT_LIST ...]]\n                     [--int-2-list INT_2_LIST INT_2_LIST]\n                     [--multi-type-tuple MULTI_TYPE_TUPLE MULTI_TYPE_TUPLE MULTI_TYPE_TUPLE]\n                     [--actions {Initialize/init,Execute/exec} [{Initialize/init,Execute/exec} ...]]\n                     [--animals {Cat/1,Dog/2} [{Cat/1,Dog/2} ...]]\n                     [--literal-list {aa,bb,11,22,Cat/1} [{aa,bb,11,22,Cat/1} ...]]\n                     [--union-list UNION_LIST [UNION_LIST ...]]\n                     [--union-with-literal UNION_WITH_LITERAL [UNION_WITH_LITERAL ...]]\n                     [--typeless-list TYPELESS_LIST [TYPELESS_LIST ...]]\n                     [--typeless-typing-list TYPELESS_TYPING_LIST [TYPELESS_TYPING_LIST ...]]\n                     [--none-bool-arg | --no-none-bool-arg]\n                     [--true-bool-arg | --no-true-bool-arg]\n                     [--false-bool-arg | --no-false-bool-arg]\n                     [--complex-arg COMPLEX_ARG] [-s SHOW [SHOW ...]]\n                     pos-arg-1 [pos-arg-2]\n\nClass doc string ==> parser description. The fields' inline/above comment ==>\nargument's help.\n\npositional arguments:\n  pos-arg-1             Field with no explicit default ==> positional\n                        arguments (default=None)\n  pos-arg-2             pos_arg() is a wrapper around dataclasses.field().The\n                        first argument (optional) is the argument default\n                        (default=5).The following keyword arguments can be any\n                        argparse.add_argument() parameter.\n\noptions:\n  -h, --help            show this help message and exit\n  --int-arg INT_ARG     Field's type and default are applied to the parser\n                        (type=int, default=1)\n  --str-enum-choice-arg {Initialize/init,Execute/exec}\n                        StrEnum ==> choice argument (type=Action,\n                        default=Initialize)\n  --int-enum-choice-arg {Cat/1,Dog/2}\n                        IntEnum ==> choice argument (type=Animal, default=Cat)\n  --literal-arg {a,b,c}\n                        Literal ==> choice argument (type=str, default=None)\n  --literal-int-arg {1,2,3}\n                        Literal's type is automatically inferred (type=int)\n  --mixed-literal {1,2,3,4,True,Cat/1}\n                        We can mix multiple literal types\n                        (type=typing.Literal[1, 2, '3', '4', True,\n                        <Animal.Cat: 1>])\n  --optional-arg OPTIONAL_ARG\n                        Optional can be used for type hinting (type=int)\n  --just-optional-arg JUST_OPTIONAL_ARG\n                        Bare optional also works (type=None)\n  --optional-choice-arg {Initialize/init,Execute/exec}\n                        Nested types are supported (type=Action)\n  --union-arg UNION_ARG\n                        Tries to convert to type in order until first success\n                        (type=typing.Union[int, float, bool])\n  --path-arg PATH_ARG   (type: Path)\n  -f FLAG_ARG, --flag-arg FLAG_ARG\n                        arg() is a wrapper around dataclasses.field().The\n                        first argument (optional) is the short argument\n                        name.The following keyword arguments can be any\n                        argparse.add_argument() parameter.\n  -r REQUIRED_ARG, --required-arg REQUIRED_ARG\n                        E.g., required=True\n  --metavar-arg M       E.g., metavar=M\n  --int-list INT_LIST [INT_LIST ...]\n                        List type hint ==> nargs=\"+\" (type=int)\n  --int-2-list INT_2_LIST INT_2_LIST\n                        Tuple type hint ==> nargs=<tuple length> (nargs=2,\n                        type=int)\n  --multi-type-tuple MULTI_TYPE_TUPLE MULTI_TYPE_TUPLE MULTI_TYPE_TUPLE\n                        We can use multiple types (type=typing.Union[int,\n                        float, str])\n  --actions {Initialize/init,Execute/exec} [{Initialize/init,Execute/exec} ...]\n                        List[Enum] ==> choices with nargs=\"+\" (nargs=+,\n                        type=Action)\n  --animals {Cat/1,Dog/2} [{Cat/1,Dog/2} ...]\n                        List[Enum] ==> choices with nargs=\"+\" (nargs=+,\n                        type=Animal)\n  --literal-list {aa,bb,11,22,Cat/1} [{aa,bb,11,22,Cat/1} ...]\n                        List[Literal] ==> choices with nargs=\"+\"\n  --union-list UNION_LIST [UNION_LIST ...]\n                        (type: typing.Union[int, float, str, bool])\n  --union-with-literal UNION_WITH_LITERAL [UNION_WITH_LITERAL ...]\n                        (type: typing.Union[typing.Literal['a', 'b', 1, 2],\n                        float, bool])\n  --typeless-list TYPELESS_LIST [TYPELESS_LIST ...]\n                        If list type is unspecified, then it uses argparse\n                        default (type=None)\n  --typeless-typing-list TYPELESS_TYPING_LIST [TYPELESS_TYPING_LIST ...]\n                        typing.List or list are supported\n  --none-bool-arg, --no-none-bool-arg\n                        boolean args ==> argparse.BooleanOptionalAction\n                        (type=bool)\n  --true-bool-arg, --no-true-bool-arg\n                        We can set any default value (default: True)\n  --false-bool-arg, --no-false-bool-arg\n                        (type: bool) (default: False)\n  --complex-arg COMPLEX_ARG\n                        (type: complex)\n  -s SHOW [SHOW ...], --show SHOW [SHOW ...]\n                        We used this argument for the README example. Note\n                        that comments above the arg are also included in the\n                        help of the argument. This is a convenient way to\n                        include long help messages.\n```\n\nNote that for Enums, we can use either the enum name or its value.\n<!-- execute: python examples/usage.py str-choices --actions Initialize init Execute exec -r1 -s actions -->\n```text\n$ python examples/usage.py str-choices --actions Initialize init Execute exec -r1 -s actions\nactions: [<Action.Initialize: 'init'>, <Action.Initialize: 'init'>, <Action.Execute: 'exec'>, <Action.Execute: 'exec'>]\n```\n<!-- execute: python examples/usage.py int-choices --animals Cat 1 Dog 2 -r1 -s animals -->\n```text\n$ python examples/usage.py int-choices --animals Cat 1 Dog 2 -r1 -s animals\nanimals: [<Animal.Cat: 1>, <Animal.Cat: 1>, <Animal.Dog: 2>, <Animal.Dog: 2>]\n```\n\n# Alternatives\n\n#### [mivade/argparse_dataclass](https://github.com/mivade/argparse_dataclass)\n  - Allow transforming dataclass to `ArgumentParser`.\n  - Missing features:\n    - `Enum` support\n    - `arg/pos_arg/no_arg` functionality\n    - Implicit positional argument\n    - `nargs` support\n\n#### [lebrice/simple-parsing](https://github.com/lebrice/SimpleParsing)\n  - Allow adding dataclass to `ArgumentParser` by using `parser.add_arguments()`\n  - Requires boilerplate code to create the parser\n  - Positional arguments\n  - `nargs` support\n\n### [swansonk14/typed-argument-parser](https://github.com/swansonk14/typed-argument-parser)\n  - Creating argument parser from classes and functions\n  - Rich functionality\n  - Post-processing of arguments\n  - Save/load arguments\n  - Load from dict\n\n# License\n\n[BSD-3](LICENSE)\n",
    "bugtrack_url": null,
    "license": "BSD-3-Clause",
    "summary": "Declarative `ArgumentParser` definition with `dataclass` notation.",
    "version": "0.1.4",
    "project_urls": {
        "Homepage": "https://github.com/liran-funaro/classparse"
    },
    "split_keywords": [
        "argparse",
        "dataclass"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6f7215cd8467e5f058e979e42ac4e556fda263b1b98607e8fc681c354f23738b",
                "md5": "54ef2121d7c93bd78ef416ce11bb6c63",
                "sha256": "4c08a64c6c0f19f46805c2ab90a30af6ab5cb5fc11b6c6e3c8173e968c2b145a"
            },
            "downloads": -1,
            "filename": "classparse-0.1.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "54ef2121d7c93bd78ef416ce11bb6c63",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 15031,
            "upload_time": "2023-05-24T06:17:53",
            "upload_time_iso_8601": "2023-05-24T06:17:53.644862Z",
            "url": "https://files.pythonhosted.org/packages/6f/72/15cd8467e5f058e979e42ac4e556fda263b1b98607e8fc681c354f23738b/classparse-0.1.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d337cce3269c3d65569f962fbabc3bfe5d678fcd0daa43b788220dae910cb930",
                "md5": "d2d790f86c2531495af721aa808786b0",
                "sha256": "5f4f93a35ae5f01aa797c14c34ec27f1832df4603ae9303fa3851c431412d2d8"
            },
            "downloads": -1,
            "filename": "classparse-0.1.4.tar.gz",
            "has_sig": false,
            "md5_digest": "d2d790f86c2531495af721aa808786b0",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 17480,
            "upload_time": "2023-05-24T06:17:56",
            "upload_time_iso_8601": "2023-05-24T06:17:56.571124Z",
            "url": "https://files.pythonhosted.org/packages/d3/37/cce3269c3d65569f962fbabc3bfe5d678fcd0daa43b788220dae910cb930/classparse-0.1.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-24 06:17:56",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "liran-funaro",
    "github_project": "classparse",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "classparse"
}
        
Elapsed time: 0.29181s