-
First Check
Commit to Help
Example Codeimport click
import typer
import typer.main
from typer.testing import CliRunner
def click_type_pass_through(f):
@wraps(f)
def wrapper(*args, **kwds):
if isinstance(kwds["annotation"], click.ParamType):
return kwds["annotation"]
else:
return f(*args, **kwds)
return wrapper
typer.main.get_click_type = click_type_pass_through(typer.main.get_click_type)
app = typer.Typer()
def config_file_callback(ctx, param, value):
ctx.default_map = {"name": {"first": "Camila", "last": "Cabello"}}
return value
def name_callback(ctx, param, value):
if isinstance(value, dict):
return value
first, last = value.split()
return {"first": first, "last": last}
@app.command()
def main(
config: str = typer.Option("--config", callback=config_file_callback),
name: click.UNPROCESSED = typer.Option("--name", callback=name_callback),
):
print(f"User: {name['first']} {name['last']}")
runner = CliRunner()
result = runner.invoke(app, args)
assert "User: Camila Cabello" in result.stdout DescriptionI want to use a combination of callbacks to define more complex config in a file. For a real-world example using Typer, see deepyaman/kedro-argo@d2eaf1b. For an example using Click (that I referenced for my Typer implementation), see https://github.com/kedro-org/kedro/blob/5906440/kedro/framework/cli/project.py#L329-L342. Wanted SolutionI would like to avoid patching Wanted Codeimport click
import typer
from typer.testing import CliRunner
app = typer.Typer()
def config_file_callback(ctx, param, value):
ctx.default_map = {"name": {"first": "Camila", "last": "Cabello"}}
return value
def name_callback(ctx, param, value):
if isinstance(value, dict):
return value
first, last = value.split()
return {"first": first, "last": last}
@app.command()
def main(
config: str = typer.Option("--config", callback=config_file_callback),
name: click.UNPROCESSED = typer.Option("--name", callback=name_callback),
):
print(f"User: {name['first']} {name['last']}")
runner = CliRunner()
result = runner.invoke(app, args)
assert "User: Camila Cabello" in result.stdout AlternativesThis could be addressed by the broader #443. #446 presents a simpler, more targeted solution. Operating SystemmacOS Operating System DetailsDarwin Kernel Version 21.5.0: Tue Apr 26 21:08:37 PDT 2022; root:xnu-8020.121.3~4/RELEASE_ARM64_T6000 arm64 Typer Version0.6.1 Python Version3.10.5 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Thanks! Support for this was added in #583, the new docs are here: https://typer.tiangolo.com/tutorial/parameter-types/custom-types/, it's available in Typer |
Beta Was this translation helpful? Give feedback.
Thanks! Support for this was added in #583, the new docs are here: https://typer.tiangolo.com/tutorial/parameter-types/custom-types/, it's available in Typer
0.8.0
, just released. 🎉