swansonk14 / typed-argument-parser

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

[suggestion] Class variable arguments with multiline defaults do not respect help comments #130

Closed TibiIius closed 2 weeks ago

TibiIius commented 7 months ago

Imagine the following:

from tap import Tap
import os

class MyParser(Tap):
  some_arg_with_default: str = "I'm a default"
  """This is some arg"""

  other_arg_with_env: int = os.environ.get("SHORT_ENV", 1)
  """This will be shown"""

  other_arg_with_way_too_long_env: str = os.environ.get(
    "SOME_VERY_LONG_ENV_VAR", "default"
  )
  """I will not be shown"""
  # Neither will I

  yet_another_arg_with_workaround: str = os.environ.get(
    """I will be shown"""
    "SOME_VERY_LONG_ENV_VAR", "default"
  )

my_parser = MyParser().parse_args()

Output:

[tim@fedora-laptop] ❯ python3 main.py --help
usage: main.py [--some_arg_with_default SOME_ARG_WITH_DEFAULT]
               [--other_arg_with_env OTHER_ARG_WITH_ENV]
               [--other_arg_with_way_too_long_env OTHER_ARG_WITH_WAY_TOO_LONG_ENV]
               [--yet_another_arg_with_workaround YET_ANOTHER_ARG_WITH_WORKAROUND]
               [-h]

options:
  --some_arg_with_default SOME_ARG_WITH_DEFAULT
                        (str, default=I'm a default) This is some arg
  --other_arg_with_env OTHER_ARG_WITH_ENV
                        (int, default=1) This will be shown
  --other_arg_with_way_too_long_env OTHER_ARG_WITH_WAY_TOO_LONG_ENV
                        (str, default=default) SOME_VERY_LONG_ENV_VAR
  --yet_another_arg_with_workaround YET_ANOTHER_ARG_WITH_WORKAROUND
                        (str, default=default) I will be shown
  -h, --help            show this help message and exit

I'm currently facing this issue when I set defaults based on current environment variables to offer simpler configuration inside a containerized environment. Comments underneath are not getting picked up as help strings in this case unless you place them like in the fourth cast above. In my case, black often enforces linebreaks in these situations. Given its popularity and conventions like PEP 8's maximum line length, addressing this would help users be consistent with coding styles across the whole project and not either lose this super neat functionality or having to place docstring comments in a weird spot.

martinjm97 commented 6 months ago

Hi @TibiIius,

It seems like the source code parser doesn't handle the case of multi-line argument declarations. This is not intended behavior. Thank you for raising this issue!

Best, JK

swansonk14 commented 2 weeks ago

Hi @TibiIius,

This has now been fixed in https://github.com/swansonk14/typed-argument-parser/pull/148. Thank you again for raising this issue!

Best, JK