Completers¶
Typer and click provide tab-completion hooks for individual
parameters. As with parsers
custom completion logic can be
implemented for custom parameter types and added to the annotation of the parameter.
Previous versions of Typer supporting click 7 used the
autocompletion argument to provide completion logic, Typer still supports this, but
passing shell_complete
to the annotation is the preferred way to do this.
This package provides some completer functions and classes that work with common Django types:
models: Complete model object field strings using
ModelObjectCompleter
.django apps: Complete app labels or names using
app_labels()
.commands: Complete Django command names using
commands()
.databases: Complete Django database names using
databases()
.import paths: Complete python import paths using
import_paths()
.paths: Complete file and directory paths using
paths()
.directories: Complete directories using
directories()
.media paths: Complete Django media paths using
media_paths()
.static paths: Complete Django static paths using
static_paths()
.languages: Complete Django language names using
languages()
.settings: Complete Django settings variable names using
setting()
.
- django_typer.completers.chain(completer, *completers, first_match=False, allow_duplicates=False)[source]¶
Run through the given completers and return the items from the first one, or all of them if first_match is False.
Note
This function is also useful for filtering out previously supplied duplicate values for completers that do not natively support that:
shell_complete=chain( complete_import_path, allow_duplicates=False )
- Parameters:
completer (Callable[[Context, Parameter, str], List[CompletionItem]]) – The first completer to use (must be at least one!)
completers (Callable[[Context, Parameter, str], List[CompletionItem]]) – The completers to use
first_match (bool) – If true, return only the matches from the first completer that finds completions. Default: False
allow_duplicates (bool) – If False (default) remove completions from previously provided values.
- django_typer.completers.these_strings(strings, allow_duplicates=False)[source]¶
Get a completer that provides completion logic that matches the allowed strings.
- Parameters:
strings (Callable[[], Sequence[Any | Tuple[Any, Any]] | KeysView[Any] | ValuesView[Any] | ItemsView[Any, Any] | Generator[Any | Tuple[Any, Any], None, None]] | Sequence[Any | Tuple[Any, Any]] | KeysView[Any] | ValuesView[Any] | ItemsView[Any, Any] | Generator[Any | Tuple[Any, Any], None, None]) – A sequence of allowed strings or a callable that generates a sequence of allowed strings. If the sequence contains 2-tuples the second element is used as the help text for the completion item.
allow_duplicates (bool) – Whether or not to allow duplicate values. Defaults to False.
- Returns:
A completer function.
- django_typer.completers.apps.app_labels(ctx, param, incomplete)[source]¶
A case-sensitive completer for Django app labels or names. The completer prefers labels but names will also work.
import typing as t import typer from django_typer.management import TyperCommand from django_typer.parsers import parse_app_label from django_typer.completers import complete_app_label class Command(TyperCommand): def handle( self, django_apps: t.Annotated[ t.List[AppConfig], typer.Argument( parser=parse_app_label, shell_complete=complete_app_label, help=_("One or more application labels.") ) ] ): ...
- Parameters:
- Returns:
A list of matching app labels or names. Labels already present for the parameter on the command line will be filtered out.
- Return type:
- django_typer.completers.cmd.commands(allow_duplicates=False)¶
A completer that completes management command names.
- Parameters:
allow_duplicates (bool) – Whether or not to allow duplicate values. Defaults to False.
- Returns:
A completer function.
- django_typer.completers.db.databases(allow_duplicates=False)¶
A completer that completes Django database aliases configured in settings.DATABASES.
- Parameters:
allow_duplicates (bool) – Whether or not to allow duplicate values. Defaults to False.
- Returns:
A completer function.
- class django_typer.completers.model.ModelObjectCompleter(model_or_qry, lookup_field=None, help_field=None, query=None, limit=50, case_insensitive=False, distinct=True, order_by=[], use_choices=True)[source]¶
A completer for generic Django model objects. This completer will work for most Django core model field types where completion makes sense.
This completer currently supports the following field types and their subclasses:
DateField
(Must use ISO 8601: YYYY-MM-DD)TimeField
(Must use ISO 8601: HH:MM:SS.ssssss)DateTimeField
(Must use ISO 8601: YYYY-MM-DDTHH:MM:SS.ssssss±HH:MM)DurationField
(Must use ISO 8601: YYYY-MM-DDTHH:MM:SS.ssssss±HH:MM)
Note
The queries used by this completer will make use of column indexes. Completions should be fast even for large data.
The completer query logic is pluggable, but the defaults cover most use cases. The limit field is important. It defaults to 50 meaning if more than 50 potential completions are found only the first 50 will be returned and there will be no indication to the user that there are more. This is to prevent the shell from becoming unresponsive when offering completion for large tables.
To use this completer, pass an instance of this class to the shell_complete argument of a typer.Option or typer.Argument:
from django_typer.completers import ModelObjectCompleter class Command(TyperCommand): def handle( self, model_obj: Annotated[ MyModel, typer.Argument( shell_complete=ModelObjectCompleter(MyModel, lookup_field="name"), help=_("The model object to use.") ) ] ): ...
Note
See also
model_parser_completer()
for a convenience function that returns a configured parser and completer for a model object and helps reduce boilerplate.- Parameters:
model_or_qry (Type[Model] | QuerySet) – The Django model class or a queryset to filter against.
lookup_field (str) – The name of the model field to use for lookup.
help_field (str | None) – The name of the model field to use for help text or None if no help text should be provided.
query (Callable[[...], Q | Tuple[Q, int]]) –
A callable that accepts any named arguments and returns a Q object. It will be passed:
incomplete the incomplete string
lookup_field the name of the model field to use for lookup
queryset the base queryset to use for completions
context the click context
parameter the click parameter
completer an instance of this ModelObjectCompleter class
It is not required to use those arguments, but they are available.
It must return a Q object to use for filtering the queryset. The default query will use the relevant query builder depending on the lookup field class.
..note:
The query builder function may also return a second integer offset value. This value will be used to adjust the index into the completion strings when we concatenate the incomplete string with the lookup field value - see UUID which has to allow for - to be missing
limit (int | None) – The maximum number of completion items to return. If None, all matching items will be returned. When offering completion for large tables you’ll want to set this to a reasonable limit. Default: 50
case_insensitive (bool) – Whether or not to perform case insensitive matching when completing text-based fields. Defaults to False.
distinct (bool) – Whether or not to filter out duplicate values. Defaults to True. This is not the same as calling distinct() on the queryset - which will happen regardless - but rather whether or not to filter out values that are already given for the parameter on the command line.
order_by (List[str]) – The order_by parameter to prioritize completions in. By default the default queryset ordering will be used for the model.
use_choices (bool) – Whether or not to use the field choices for completion. If True, matches to choice values coerced to strings will be returned. If False, the field’s default query builder will be used instead.
- django_typer.completers.model.date_query(incomplete, lookup_field, **_)[source]¶
Default completion query builder for date fields. This method will return a Q object that will match any value that starts with the incomplete date string. All dates must be in ISO8601 format (YYYY-MM-DD).
This query will utilize the database index if one exists.
- Parameters:
- Returns:
A Q object to use for filtering the queryset.
- Raises:
ValueError – If the incomplete string is not a valid partial date.
AssertionError – If the incomplete string is not a valid partial date.
- Return type:
Q
- django_typer.completers.model.datetime_query(incomplete, lookup_field, **_)[source]¶
Default completion query builder for datetime fields. This method will return a Q object that will match any value that starts with the incomplete datetime string. All dates must be in ISO8601 format (YYYY-MM-DDTHH:MM:SS.ssssss±HH:MM).
This query will utilize the database index if one exists.
- Parameters:
- Returns:
A Q object to use for filtering the queryset.
- Raises:
ValueError – If the incomplete string is not a valid partial datetime.
AssertionError – If the incomplete string is not a valid partial datetime.
- Return type:
Q
- django_typer.completers.model.duration_query(incomplete, lookup_field, queryset, **_)[source]¶
Default completion query builder for duration fields. This method will return a Q object that will match any value that is greater than the incomplete duration string (or less if negative). Duration strings are formatted in a subset of the ISO8601 standard. Only day, hours, minutes and fractional seconds are supported. Year, week and month specifiers are not.
This query will utilize the database index if one exists.
- Parameters:
- Returns:
A Q object to use for filtering the queryset.
- Raises:
ValueError – If the incomplete string is not a valid partial duration.
AssertionError – If the incomplete string is not a valid partial duration.
- Return type:
Q
- django_typer.completers.model.float_query(incomplete, lookup_field, queryset, **_)[source]¶
The default completion query builder for float fields. This method will return a Q object that will match any value that starts with the incomplete string. For example, if the incomplete string is “1.1”, the query will match 1.1 <= float(incomplete) < 1.2
This query will utilize the database index if one exists.
- Parameters:
- Returns:
A Q object to use for filtering the queryset.
- Raises:
ValueError – If the incomplete string is not a valid float.
TypeError – If the incomplete string is not a valid float.
- Return type:
Q
- django_typer.completers.model.get_date_bounds(incomplete)[source]¶
Turn an incomplete YYYY-MM-DD date string into upper and lower bound date objects.
- django_typer.completers.model.get_time_bounds(incomplete)[source]¶
Turn an incomplete HH::MM::SS.ssssss time string into upper and lower bound time objects.
- django_typer.completers.model.int_query(incomplete, lookup_field, queryset, **_)[source]¶
The default completion query builder for integer fields. This method will return a Q object that will match any value that starts with the incomplete string. For example, if the incomplete string is “1”, the query will match 1, 10-19, 100-199, 1000-1999, etc.
This query will utilize the database index if one exists.
- Parameters:
- Returns:
A Q object to use for filtering the queryset.
- Raises:
ValueError – If the incomplete string is not a valid integer.
TypeError – If the incomplete string is not a valid integer.
- Return type:
Q
- django_typer.completers.model.text_query(incomplete, lookup_field, case_insensitive=False, **_)[source]¶
The default completion query builder for text-based fields. This method will return a Q object that will match any value that starts with the incomplete string. Case sensitivity is determined by the case_insensitive constructor parameter.
This query will utilize the database index if one exists.
- django_typer.completers.model.time_query(incomplete, lookup_field, **_)[source]¶
Default completion query builder for time fields. This method will return a Q object that will match any value that starts with the incomplete time string. All times must be in ISO 8601 format (HH:MM:SS.ssssss).
This query will utilize the database index if one exists.
- Parameters:
- Returns:
A Q object to use for filtering the queryset.
- Raises:
ValueError – If the incomplete string is not a valid partial time.
AssertionError – If the incomplete string is not a valid partial time.
- Return type:
Q
- django_typer.completers.model.uuid_query(incomplete, lookup_field, **_)[source]¶
The default completion query builder for UUID fields. This method will return a Q object that will match any value that starts with the incomplete string. The incomplete string will be stripped of all non-alphanumeric characters and padded with zeros to 32 characters. For example, if the incomplete string is “a”, the query will match a0000000-0000-0000-0000-000000000000 to affffffff-ffff-ffff-ffff-ffffffffffff.
This query will utilize the database index if one exists.
- Parameters:
- Returns:
A 2-tuple where the first element is the Q object to use for filtering the queryset and the second is the integer offset into the incomplete string where the completion characters should be concatenated.
- Raises:
ValueError – If the incomplete string is too long or contains invalid UUID characters. Anything other than (0-9a-fA-F).
- Return type:
- django_typer.completers.path.directories(ctx, param, incomplete, *, dir_only=True, root=None)¶
A completer that completes a directory path (but not files). Relative incomplete paths are interpreted relative to the current working directory.
- django_typer.completers.path.import_paths(ctx, param, incomplete, root=None)[source]¶
A completer that completes a python dot import path string based on sys.path.
- Parameters:
- Returns:
A list of available matching import paths
- Return type:
- django_typer.completers.path.media_paths(ctx, param, incomplete, dir_only=None, *, root=functools.partial(<function _settings_path>, name='MEDIA_ROOT'))¶
Complete media file paths.
- Parameters:
- Returns:
A list of available matching directories
- Return type:
- django_typer.completers.path.paths(ctx, param, incomplete, dir_only=None, root=None)[source]¶
A completer that completes a path. Relative incomplete paths are interpreted relative to the current working directory.
- Parameters:
ctx (Context) – The click context.
param (Parameter) – The click parameter.
incomplete (str) – The incomplete string.
dir_only (bool | None) – Restrict completions to paths to directories only, otherwise complete directories or files.
root (Callable[[], Path | None] | Path | None) – Restrict completions to this root path.
- Returns:
A list of available matching directories
- Return type:
- django_typer.completers.path.static_paths(ctx, param, incomplete, dir_only=None, *, root=functools.partial(<function _settings_path>, name='STATIC_ROOT'))¶
Complete static file paths.
- Parameters:
- Returns:
A list of available matching directories
- Return type:
Completers that complete items involving Django’s settings.