Skip to content

API to CLI

Generate a CLI template from a class public API.

This utility builds a CLI representation of a class by delegating to PublicAPI.to_cli_template(). The resulting template can either be returned as a string or written to a file.

Parameters:

Name Type Description Default
cls type

Target class to convert.

required
skip_methods list[str]

Methods to exclude.

[]
only_methods list[str]

If provided, only these methods are included.

[]
return_type list[str]

Filter methods by return type.

[]
output str

If provided, path to a file where the generated template will be written.

None
**kwargs

Additional arguments forwarded to to_cli_template().

{}

Returns:

Type Description
Union[None, str]

str or None: - Returns the generated template if output is None. - Otherwise writes to file and returns None.

Notes
  • The file is overwritten if it already exists.
Source code in src/qargparse/utils.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def api_to_cli_template(
        cls: type, 
        skip_methods: List[str]=[],
        only_methods: List[str]=[],
        return_type: List[str]=[],
        output: str | None = None,
        **kwargs
        ) -> Union[None, str]:
    """Generate a CLI template from a class public API.

    This utility builds a CLI representation of a class by delegating
    to `PublicAPI.to_cli_template()`. The resulting template can either
    be returned as a string or written to a file.

    Args:
        cls (type): Target class to convert.
        skip_methods (list[str], optional): Methods to exclude.
        only_methods (list[str], optional): If provided, only these methods are included.
        return_type (list[str], optional): Filter methods by return type.
        output (str, optional): If provided, path to a file where the
                                generated template will be written.
        **kwargs: Additional arguments forwarded to `to_cli_template()`.

    Returns:
        str or None:
            - Returns the generated template if `output` is None.
            - Otherwise writes to file and returns None.

    Notes:
        - The file is overwritten if it already exists.
    """
    from qargparse.public_api import PublicAPI

    template = PublicAPI(
        cls=cls, 
        skip_methods=skip_methods, 
        only_methods=only_methods,
        return_type=return_type
    ).to_cli_template(**kwargs)

    if output is None:
        return template

    with open(output, 'w') as f:
        f.write(output)

Configuration options for qargparse CLI template generation.

This module defines the immutable configuration object used when generating CLI templates from a reflected public API.

The ToCliTemplateOpts dataclass centralizes all customization flags that control how parameters are rendered into CLI arguments, including:

  • Argument grouping behavior
  • Parameter deduplication strategies
  • Help message formatting
  • Parameter skipping or uniquification rules

The object is frozen and uses structural replacement (dataclasses.replace) to safely derive modified configurations.

ToCliTemplateOpts

Options controlling CLI template generation.

This immutable configuration object defines how a PublicAPI instance is translated into qargparse argument definitions.

Attributes:

Name Type Description
make_grp bool

Whether to create argument groups per method in the generated CLI template.

dedup_kwargs_strategy DeduplicationStrategy

Strategy used when multiple methods share parameters. Determines whether parameters are aliased or regrouped.

param_prefix str

Prefix used for named CLI parameters (e.g., "--").

param_desc bool

Whether to include parameter descriptions in help messages.

param_default bool

Whether to include parameter default value, if any. WARNING: with REGROUP dedup strategy, the default value may not correspond to the expected on!

skip_params List[str]

Parameter names to skip during CLI generation.

uniquize_params List[str]

Parameter names that must be uniquified when shared across multiple methods.

help_skip_params bool

Whether skipped parameters should still appear in help output.

Raises:

Type Description
TypeError

If any attribute has an invalid type.

Source code in src/qargparse/opts/to_cli_template.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
@dataclass(frozen=True, slots=True, kw_only=True)
class ToCliTemplateOpts:
    """Options controlling CLI template generation.

    This immutable configuration object defines how a PublicAPI
    instance is translated into qargparse argument definitions.

    Attributes:
        make_grp (bool):
            Whether to create argument groups per method in the
            generated CLI template.

        dedup_kwargs_strategy (DeduplicationStrategy):
            Strategy used when multiple methods share parameters.
            Determines whether parameters are aliased or regrouped.

        n_min_dedup (int)
            Minimum number of duplicated parameters ti regroup
            them if DeduplicationStrategy is REGROUP (default: 2)

        param_prefix (str):
            Prefix used for named CLI parameters (e.g., "--").

        param_desc (bool):
            Whether to include parameter descriptions in help messages.

        param_default (bool):
            Whether to include parameter default value, if any.
            WARNING: with REGROUP dedup strategy, the default value may
            not correspond to the expected on!

        skip_params (List[str]):
            Parameter names to skip during CLI generation.

        uniquize_params (List[str]):
            Parameter names that must be uniquified when shared
            across multiple methods.

        help_skip_params (bool):
            Whether skipped parameters should still appear in help output.

    Raises:
        TypeError: If any attribute has an invalid type.
    """
    make_grp: bool = field(default=True)
    dedup_kwargs_strategy: DeduplicationStrategy = field(default=DeduplicationStrategy.ALIAS)
    n_min_dedup: int = field(default=2)
    param_prefix: str = field(default="--")
    param_desc: bool = field(default=True)
    param_default: bool = field(default=True)
    skip_params: List[str] = field(default_factory=list)
    uniquize_params: List[str] = field(default_factory=list)
    help_skip_params: bool = field(default=True)

    def set_skipped_and_uniquize_params(self, public_api: 'PublicAPI'):  # type: ignore # noqa: F821
        """Compute deduplicated parameter handling rules.

        Determines which parameters should be skipped or uniquified
        based on the selected deduplication strategy and the
        parameters exposed by the provided PublicAPI.

        Duplicate parameters are defined as parameters shared by more
        than one method, excluding special ARGS and KWARGS entries.

        Args:
            public_api (PublicAPI):
                The reflected API containing parameter metadata.

        Returns:
            ToCliTemplateOpts:
                A new configuration instance with updated
                ``skip_params`` and ``uniquize_params`` fields,
                derived using dataclasses.replace().

        Raises:
            ValueError: If the deduplication strategy is unsupported.
        """
        d_param = public_api.parameters
        dup_params = []
        uniquize_params = []
        for k, v in d_param.items():
            if k not in [ARGS, KWARGS]:
                if len(v) > 1:
                    if len(v) >= self.n_min_dedup:
                        dup_params.append(k)
                    else:
                        uniquize_params.append(k)
        match self.dedup_kwargs_strategy:
            case DeduplicationStrategy.REGROUP:
                skip_params = self.skip_params + dup_params
                uniquize_params = self.uniquize_params + uniquize_params
            case DeduplicationStrategy.ALIAS:
                skip_params = self.skip_params
                uniquize_params = self.uniquize_params + dup_params + uniquize_params  
        return replace(self, skip_params=skip_params, uniquize_params=uniquize_params)

set_skipped_and_uniquize_params(public_api)

Compute deduplicated parameter handling rules.

Determines which parameters should be skipped or uniquified based on the selected deduplication strategy and the parameters exposed by the provided PublicAPI.

Duplicate parameters are defined as parameters shared by more than one method, excluding special ARGS and KWARGS entries.

Parameters:

Name Type Description Default
public_api PublicAPI

The reflected API containing parameter metadata.

required

Returns:

Name Type Description
ToCliTemplateOpts

A new configuration instance with updated skip_params and uniquize_params fields, derived using dataclasses.replace().

Raises:

Type Description
ValueError

If the deduplication strategy is unsupported.

Source code in src/qargparse/opts/to_cli_template.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def set_skipped_and_uniquize_params(self, public_api: 'PublicAPI'):  # type: ignore # noqa: F821
    """Compute deduplicated parameter handling rules.

    Determines which parameters should be skipped or uniquified
    based on the selected deduplication strategy and the
    parameters exposed by the provided PublicAPI.

    Duplicate parameters are defined as parameters shared by more
    than one method, excluding special ARGS and KWARGS entries.

    Args:
        public_api (PublicAPI):
            The reflected API containing parameter metadata.

    Returns:
        ToCliTemplateOpts:
            A new configuration instance with updated
            ``skip_params`` and ``uniquize_params`` fields,
            derived using dataclasses.replace().

    Raises:
        ValueError: If the deduplication strategy is unsupported.
    """
    d_param = public_api.parameters
    dup_params = []
    uniquize_params = []
    for k, v in d_param.items():
        if k not in [ARGS, KWARGS]:
            if len(v) > 1:
                if len(v) >= self.n_min_dedup:
                    dup_params.append(k)
                else:
                    uniquize_params.append(k)
    match self.dedup_kwargs_strategy:
        case DeduplicationStrategy.REGROUP:
            skip_params = self.skip_params + dup_params
            uniquize_params = self.uniquize_params + uniquize_params
        case DeduplicationStrategy.ALIAS:
            skip_params = self.skip_params
            uniquize_params = self.uniquize_params + dup_params + uniquize_params  
    return replace(self, skip_params=skip_params, uniquize_params=uniquize_params)

Deduplication strategies for shared CLI parameters.

This module defines the available strategies used when multiple API methods expose parameters with the same name.

These strategies control how qargparse resolves naming conflicts during CLI template generation.

DeduplicationStrategy

Bases: Enum


              flowchart TD
              src.qargparse.opts.deduplication_strategy.DeduplicationStrategy[DeduplicationStrategy]

              

              click src.qargparse.opts.deduplication_strategy.DeduplicationStrategy href "" "src.qargparse.opts.deduplication_strategy.DeduplicationStrategy"
            

Strategies for handling duplicated parameters across methods.

When multiple methods share parameters with the same name, a deduplication strategy determines how those parameters are represented in the generated CLI.

Attributes:

Name Type Description
REGROUP str

Shared parameters are regrouped and defined once. Methods reuse the same CLI argument.

ALIAS str

Shared parameters are duplicated and uniquified (e.g., prefixed with the method name).

Source code in src/qargparse/opts/deduplication_strategy.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class DeduplicationStrategy(Enum):
    """Strategies for handling duplicated parameters across methods.

    When multiple methods share parameters with the same name,
    a deduplication strategy determines how those parameters
    are represented in the generated CLI.

    Attributes:
        REGROUP (str):
            Shared parameters are regrouped and defined once.
            Methods reuse the same CLI argument.

        ALIAS (str):
            Shared parameters are duplicated and uniquified
            (e.g., prefixed with the method name).
    """
    REGROUP: str = DEDUP_STRAT_REGROUP
    ALIAS: str = DEDUP_STRAT_ALIAS