_argcomplete.py
Overview
`_argcomplete.py` is a utility module designed to enable **bash-completion support for Python command-line applications** that use the `argparse` library. It leverages the external package **argcomplete** (if installed) to provide intelligent tab completion for command-line arguments, especially for file and directory paths.
The module's main purpose is to simplify the integration of argcomplete's bash-completion features by providing:
A
try_argcomplete()function that wraps the call to argcomplete.autocomplete() safely, enabling completion if argcomplete is available and the environment is configured correctly.A
filescompleterutility designed to provide fast, bash-like file and directory path completion for positional arguments.Clear instructions and debugging tips to help developers integrate and troubleshoot argcomplete support in their applications.
Detailed Documentation
Classes
FastFilesCompleter
A callable class that provides fast file and directory name completion. It is intended to be assigned as the `.completer` attribute on `argparse` positional argument definitions to enhance user experience during bash completion.
Constructor
FastFilesCompleter(directories: bool = True) -> None
Parameters:
directories(bool): IfTrue(default), directories will be completed with a trailing slash (/) to mimic bash behavior.
Description:
Initializes the completer. Thedirectoriesflag controls whether directories are appended with a slash.
Call Method
__call__(prefix: str, **kwargs: Any) -> list[str]
Parameters:
prefix(str): The current command-line token that needs to be completed.**kwargs(Any): Additional keyword arguments (ignored).
Returns:
list[str]: A list of possible completions matching the prefix.
Description:
This method is invoked by argcomplete during tab completion. It performs the following logic:Determines the directory portion of the prefix to correctly strip it from the results.
Uses
glob.globto find matches for the prefix, supporting wildcard characters*and?.If the prefix is a directory or ends with a path separator, it also includes hidden files (
.*).Appends a slash (
/) to directory names in the completion list.Returns the list of completions relative to the prefix directory.
Usage Example:
import argparse
from _argcomplete import filescompleter, try_argcomplete
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='*').completer = filescompleter
try_argcomplete(parser)
args = parser.parse_args()
Functions
try_argcomplete
try_argcomplete(parser: argparse.ArgumentParser) -> None
Parameters:
parser(argparse.ArgumentParser): The argument parser instance on which argcomplete should be activated.
Returns:
None
Description:
Detects if the environment variable_ARGCOMPLETEis set (indicating a completion request), and if so, activates argcomplete'sautocomplete()function on the provided parser. This enables bash completion for the application.Behavior:
If argcomplete is installed and
_ARGCOMPLETEis set in the environment:Imports
argcomplete.completersand callsargcomplete.autocomplete(parser, always_complete_options=False).
Otherwise, it defines a no-op function to avoid errors in environments without argcomplete.
Usage Example:
import argparse
from _argcomplete import try_argcomplete
parser = argparse.ArgumentParser()
try_argcomplete(parser)
args = parser.parse_args()
Important Implementation Details
The module uses the environment variable
_ARGCOMPLETEas a flag to detect when bash completion is being invoked.It relies on
argcompleteversion >= 0.5.6 for Python 3.2/3.3 compatibility.The
FastFilesCompleterclass uses theglobmodule to efficiently match filesystem entries, mimicking bash’s behavior, including handling hidden files and directories.The trailing slash appended to directories during completion is an important UX feature that informs users that the completion is a directory and allows further tab completion inside it.
The module gracefully falls back if
argcompleteis not installed or_ARGCOMPLETEis not set, making it safe to import and use in all environments without causing runtime errors.The file includes detailed instructions in the docstring to help developers enable argcomplete support in their own applications, including how to debug common issues.
Interaction with the System
This file is intended to be imported by the main CLI application module or any module that sets up
argparseargument parsing.It does not modify the parser or arguments itself but provides utilities (
try_argcompleteandfilescompleter) to be used alongsideargparse.It interacts with the argcomplete package, which must be installed separately.
When enabled, the bash completion system calls into this module indirectly through environment variables and the argcomplete bash setup script.
The
filescompleteris designed to be assigned as a.completerattribute on specific arguments needing file path completions.
Usage Summary
Typical minimal integration:
from _argcomplete import try_argcomplete, filescompleter
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('paths', nargs='*').completer = filescompleter
try_argcomplete(parser)
args = parser.parse_args()
This enables bash completion for your CLI application, with file path completion on the `paths` argument.
Visual Diagram
classDiagram
class FastFilesCompleter {
+directories: bool
+__init__(directories: bool)
+__call__(prefix: str, **kwargs) list~str~
}
class try_argcomplete {
+try_argcomplete(parser: argparse.ArgumentParser)
}
FastFilesCompleter <.. filescompleter : instance
try_argcomplete ..> argparse.ArgumentParser : parameter
Summary
`_argcomplete.py` is a lightweight, robust integration helper that enables bash completion support for Python CLI applications using `argparse` and `argcomplete`. It provides a fast file completer class and a safe entry point to activate argcomplete’s features, along with helpful documentation on installation and debugging. This module improves user experience of command-line tools by facilitating intuitive tab-completion of arguments with minimal developer effort.