pydantic-argparse icon indicating copy to clipboard operation
pydantic-argparse copied to clipboard

Add possiblity to address the same option via several alias names

Open vadimbo opened this issue 1 year ago • 3 comments

It would be nice to have the possibility to define in the pydantic.BaseModel Field definition the possible names for the cli arguments. It would be possible to have both: the short and long versions of the same argument.

example:

class Arguments(pydantic.BaseModel):
    debug: bool = Field (..., description="Shows the debug information", alias="my-custom-debug")

above would give the possibility to specify the argument in the command line as command --my-custom-debug

How to add the short version of the same argument i.e: -d

If support for aliases=('d', 'my-custom-debug') would be added it would be nice as pydantic.Field does support extra arguments Above would be interpreted to add the additional names to the parsed arguments

vadimbo avatar Mar 04 '23 12:03 vadimbo

Thanks @vadimbo

I like this idea. I've been meaning to add more customisation via the extra **kwargs that pydantic.Field provides.

I will begin working on this as soon as I finish the big changes in #34.

SupImDos avatar Mar 10 '23 13:03 SupImDos

Hi! Thank you for this project @SupImDos. I'd like to +1 this request for aliases so that we could have short arguments as well. Was curious if this enhancement is still planned? Thanks!

donaldcampbelljr avatar May 07 '24 16:05 donaldcampbelljr

@donaldcampbelljr Certainly still on my radar, but couldn't say when I'll have time to do this.

If you (or someone else reading this) were interested in a PR, the following pointers could help:

  • Update pydantic_argparse.utils.arguments.name to handle aliases provided in field.field_info.extra.
  • Update tests.utils.test_arguments.test_argument_name tests for the new behaviour
  • Add some new tests e.g., tests.functional.test_aliases

Some things to think about re: API / behaviour expectations

  • What happens if you provide alias and aliases?
  • What is the behaviour for boolean arguments
  • What is the behaviour for inverted arguments (i.e., --no-<x>)

Probably some other things I am forgetting here, but it should be relatively straight forward as long as its clear what the expectations are for the edge cases.

If you wanted a hack / escape hatch for now, you could try something like the following:

# Create parser with model
parser = pydantic_argparse.ArgumentParser(model=...)

# Add `-s` short argument for existing `--string` argument
argument = parser._option_string_actions["--string"]
argument.option_strings = ("-s", "--string")
parser._option_string_actions["-s"] = argument

I haven't tested this, but to the point the pydantic_argparse.ArgumentParser is just a subclass of Python's real argparse.ArgumentParser, so if you can update arguments for that it should be applicable here.

SupImDos avatar May 09 '24 09:05 SupImDos