-
-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
List arguments are not recognized in the context default_map #124
Comments
Hi there @maxb2 I've been running into the same bug after finding your original solution here fastapi/typer#86 (comment) I also found this thread fastapi/typer#518 which suggests adding a callback to the list-like Argument to set a default value. Modifying that non-eager callback to pull directly from from typing import Optional
import typer
import yaml
app = typer.Typer( )
def argument_list_callback(ctx: typer.Context, param: typer.CallbackParam, value: Optional[list[str]]) -> list[str]:
ctx.default_map = ctx.default_map or {}
if param.name in ctx.default_map:
default = ctx.default_map[param.name]
else:
default = []
return value if value else default
def conf_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):
if value:
typer.echo(f"Loading config file: {value}")
try:
with open(value, 'r') as f: # Load config file
conf = yaml.safe_load(f)
ctx.default_map = ctx.default_map or {} # Initialize the default map
ctx.default_map.update(conf) # Merge the config dict into default_map
except Exception as ex:
raise typer.BadParameter(str(ex))
return value
@app.command()
def main(
arg1: str,
arg2: list[str] = typer.Argument(default=None, callback=argument_list_callback),
config: str = typer.Option("", callback=conf_callback, is_eager=True),
opt1: str = typer.Option(...),
opt2: str = typer.Option("hello"),
):
typer.echo(f"{opt1} {opt2} {arg1}")
typer.echo(f"{arg2}")
if __name__ == "__main__":
app() # temp.yaml
opt1: "apple"
opt2: "pear"
arg1: "lemon"
arg2: ["oak", "aspen", "maple"] python app.py --config temp.yaml
> Loading config file: temp.yaml
> apple pear lemon
> ['oak', 'aspen', 'maple'] python app.py strawberry bear wolf snake tiger --config temp.yaml
> Loading config file: temp.yaml
> apple pear strawberry
> ['bear', 'wolf', 'snake', 'tiger'] The example doesn't work if you provide |
@jlwhelan28 thanks for the research! I'll add your |
See 1.4.0 |
First discovered in #117
The example in #117 doesn't work (you get
missing argument LABEL_NAMES
) withtyper-config
.However, if you make a similar
click
app, it works fine:Then invoked, you get:
$ python app.py [1, 2, 3] ParameterSource.DEFAULT_MAP {'my_list': [1, 2, 3]}
as expected.
The text was updated successfully, but these errors were encountered: