DRY way of writing different (sub)commands with the same arguments #730
-
First Check
Commit to Help
Example Codefrom typing import Annotated, Optional
import typer
from typer import Argument, Option
app = typer.Typer()
@app.command()
def translate(
dataset_name: Annotated[str, Argument(help="dataset name compatible with HuggingFace datasets")],
output_directory: Annotated[str, Argument(help="output directory to save the translated dataset to")],
config_name: Annotated[
Optional[str],
Option(help="optional config name for the dataset"),
] = None,
**kwargs_specific_to_this_other_cmd)
...
@app.command()
def answer(
dataset_name: Annotated[str, Argument(help="dataset name compatible with HuggingFace datasets")],
output_directory: Annotated[str, Argument(help="output directory to save the translated dataset to")],
config_name: Annotated[
Optional[str],
Option(help="optional config name for the dataset"),
] = None,
**kwargs_specific_to_this_other_cmd)
... DescriptionI have a couple of commands that are very similar in the arguments that they take on (more than a dozen), but each of them has a few that are specific to the command. Yet, I feel like I am needlessly repeating the 95% of the signature with all the arguments/options that are identical in the two functions. Not only is this unnecessarily DRY-less, but it's also prone to errors when I forget to change something in one or the other command arguments. Is there a way to have a base (abstract) signature command that others can inherit from? I tried functools.wrap but that did not yield the intended gain, because I still had to push kwargs through the signatures and then .get or .pop them. I have little hope for a solution but happy to hear that I am wrong. Hoping for a simple solution. Operating SystemLinux, Windows Operating System DetailsOS independent Typer Version0.9.0 Python Version3.10.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
How about something like: DatasetName = Annotated[str, Argument(help="dataset name compatible with HuggingFace datasets")]
OutputDirectory = Annotated[str, Argument(help="output directory to save the translated dataset to")]
ConfigName = Annotated[
Optional[str],
Option(help="optional config name for the dataset"),
]
@app.command()
def translate(
dataset_name: DatasetName,
output_directory: OutputDirectory,
config_name: ConfigName = None,
**kwargs_specific_to_this_other_cmd,
): ...
@app.command()
def answer(
dataset_name: DatasetName,
output_directory: OutputDirectory,
config_name: ConfigName = None,
**kwargs_specific_to_this_other_cmd,
): ... |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
How about something like: