Invoke callback without command for autocompletion #892
Unanswered
alexrosenfeld10
asked this question in
Questions
Replies: 1 comment
-
If I understand right, I have a simillar issue. I want my completion to depend on global options I pass via #!/usr/bin/env python
"""Test script to illustrate issue"""
from typing import Annotated
import typer
app = typer.Typer()
HOSTNAME = "localhost"
def _completions():
if HOSTNAME == "localhost":
return ["local_1", "local_2", "local_3"]
else:
return ["remote_1", "remote_2", "remote_3"] # in reality would fetch
@app.callback(invoke_without_command=True) # this arg doesn't help (isn't relevant?)
def common_args(hostname: str = "localhost"):
global HOSTNAME
HOSTNAME = hostname
@app.command()
def cmd(thing: Annotated[str, typer.Argument(autocompletion=_completions)]):
assert thing in _completions()
print(f"Getting {thing} from {HOSTNAME}")
if __name__ == "__main__":
app() $ ./typer_test.py cmd [TAB]
local_1 local_2 local_3
$ ./typer_test.py cmd local_1
Getting local_1 from localhost
$ ./typer_test.py --hostname host1 cmd local_1
╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
│ /home/foo/tmp/py/ionq/./typer_test.py:28 in cmd │
│ │
│ 25 │
│ 26 @app.command() │
│ 27 def cmd(thing: Annotated[str, typer.Argument(autocompletion=_completions)]): │
│ ❱ 28 │ assert thing in _completions() │
│ 29 │ print(f"Getting {thing} from {HOSTNAME}") │
│ 30 │
│ 31 │
│ │
│ ╭───── locals ──────╮ │
│ │ thing = 'local_1' │ │
│ ╰───────────────────╯ │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
AssertionError
$ ./typer_test.py --hostname host1 cmd remote_1
Getting remote_1 from host
$ ./typer_test.py --hostname host1 cmd [TAB]
local_1 local_2 local_3
$ ./typer_test.py --hostname host1 cmd local_ |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
Calling
get_option
raisesKeyError: 'cache'
when I tab complete onmy_cli --filter thing[TAB]
because the callback hasn't run, therefore the_global_options
dictionary is empty. I would expect it to have"cache": True
because the default parameter for theuse_cache_option
isTrue
.The impact here is the user gets an error. The obvious fix is, just populate the
_global_options
map with initial default values. However, that's not ideal, because it means users can't disable caching for tab completion. For example, I'd expect this to tab complete without hitting the cache:my_cli --no-cache --filter thing[TAB]
.Operating System
macOS
Operating System Details
No response
Typer Version
0.12.3
Python Version
3.12.3
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions