swansonk14 / typed-argument-parser

Typed argument parser for Python
MIT License
494 stars 40 forks source link

[help] Adding `version` arg to print version but bypassing required args #120

Closed alanwilter closed 10 months ago

alanwilter commented 10 months ago

How can I modify the example:

"""main.py"""

from tap import Tap

version = "0.1.0"

class SimpleArgumentParser(Tap):
    name: str  # Your name
    language: str = 'Python'  # Programming language
    package: str = 'Tap'  # Package name
    stars: int  # Number of stars
    max_stars: int = 5  # Maximum stars
    version: str = version

args = SimpleArgumentParser().parse_args()

so when doing python main.py --version it would print just "0.1.0" and not the error message complaining about missing required args?

martinjm97 commented 10 months ago

In our understanding, this use case doesn't quite match up with the argparse API. Our goal is for Tap to match the functionality of argparse closely, while exposing type hinting.

However, an alternative approach using the current API is to initialize a Tap object, setting the description argument with version information (if you want it set dynamically) or including in the docstring (if you want it set statically).

"""main.py"""
from tap import Tap 

version = "0.1.0"

class SimpleArgumentParser(Tap):
    """My simple argument parser is cool. """
    name: str  # Your name
    language: str = 'Python'  # Programming language
    package: str = 'Tap'  # Package name
    stars: int  # Number of stars
    max_stars: int = 5  # Maximum stars

args = SimpleArgumentParser(description=f'{SimpleArgumentParser.__doc__}\nversion = {version}').parse_args()

or

"""main.py"""
from tap import Tap 

class SimpleArgumentParser(Tap):
    """My simple argument parser is cool.
    version = 0.1.0"""
    name: str  # Your name
    language: str = 'Python'  # Programming language
    package: str = 'Tap'  # Package name
    stars: int  # Number of stars
    max_stars: int = 5  # Maximum stars

args = SimpleArgumentParser().parse_args()

If you run python main.py -h in either case, it will produce:

usage:  --name NAME [--package PACKAGE] [--language LANGUAGE] --stars STARS
        [--max_stars MAX_STARS] [-h]

My simple argument parser is cool. version = 0.1.0

options:
  --name NAME           (str, required)
  --package PACKAGE     (str, default=Tap)
  --language LANGUAGE   (str, default=Python)
  --stars STARS         (int, required)
  --max_stars MAX_STARS
                        (int, default=5)
  -h, --help            show this help message and exit

We hope this solves this problem. Let us know if it doesn't!

--JK

alanwilter commented 10 months ago

Thanks, I got your point.

martinjm97 commented 10 months ago

Wonderful! Happy tapping!