Skip to content

typer_config

Typer Configuration Utilities

yaml_conf_callback module-attribute

yaml_conf_callback: ConfigParameterCallback = conf_callback_factory(
    loader_transformer(
        yaml_loader,
        loader_conditional=lambda param_value: param_value,
    )
)

YAML typer config parameter callback.

Parameters:

Name Type Description Default
ctx typer.Context

typer context (automatically passed)

required
param typer.CallbackParam

typer callback parameter (automatically passed)

required
param_value TyperParameterValue

parameter value passed to typer (automatically passed)

required

Raises:

Type Description
BadParameter

bad parameter value

Returns:

Name Type Description
TyperParameterValue ConfigParameterCallback

must return back the given parameter

json_conf_callback module-attribute

json_conf_callback: ConfigParameterCallback = conf_callback_factory(
    loader_transformer(
        json_loader,
        loader_conditional=lambda param_value: param_value,
    )
)

JSON typer config parameter callback.

Parameters:

Name Type Description Default
ctx typer.Context

typer context (automatically passed)

required
param typer.CallbackParam

typer callback parameter (automatically passed)

required
param_value TyperParameterValue

parameter value passed to typer (automatically passed)

required

Raises:

Type Description
BadParameter

bad parameter value

Returns:

Name Type Description
TyperParameterValue ConfigParameterCallback

must return back the given parameter

toml_conf_callback module-attribute

toml_conf_callback: ConfigParameterCallback = conf_callback_factory(
    loader_transformer(
        toml_loader,
        loader_conditional=lambda param_value: param_value,
    )
)

TOML typer config parameter callback.

Parameters:

Name Type Description Default
ctx typer.Context

typer context (automatically passed)

required
param typer.CallbackParam

typer callback parameter (automatically passed)

required
param_value TyperParameterValue

parameter value passed to typer (automatically passed)

required

Raises:

Type Description
BadParameter

bad parameter value

Returns:

Name Type Description
TyperParameterValue ConfigParameterCallback

must return back the given parameter

dotenv_conf_callback module-attribute

dotenv_conf_callback: ConfigParameterCallback = conf_callback_factory(
    loader_transformer(
        dotenv_loader,
        loader_conditional=lambda param_value: param_value,
    )
)

Dotenv typer config parameter callback.

Parameters:

Name Type Description Default
ctx typer.Context

typer context (automatically passed)

required
param typer.CallbackParam

typer callback parameter (automatically passed)

required
param_value TyperParameterValue

parameter value passed to typer (automatically passed)

required

Raises:

Type Description
BadParameter

bad parameter value

Returns:

Name Type Description
TyperParameterValue ConfigParameterCallback

must return back the given parameter

conf_callback_factory

conf_callback_factory(
    loader: ConfigLoader,
) -> ConfigParameterCallback

Typer configuration callback factory.

Parameters:

Name Type Description Default
loader ConfigLoader

Config loader function that takes the value passed to the typer CLI and returns a dictionary that is applied to the click context's default map.

required

Returns:

Name Type Description
ConfigParameterCallback ConfigParameterCallback

Configuration parameter callback function.

Source code in typer_config/__init__.py
17
18
19
20
21
22
23
24
25
26
27
28
29
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
def conf_callback_factory(loader: ConfigLoader) -> ConfigParameterCallback:
    """Typer configuration callback factory.

    Args:
        loader (ConfigLoader): Config loader function that takes the value
            passed to the typer CLI and returns a dictionary that is
            applied to the click context's default map.

    Returns:
        ConfigParameterCallback: Configuration parameter callback function.
    """

    def _callback(
        ctx: Context, param: CallbackParam, param_value: TyperParameterValue
    ) -> TyperParameterValue:
        """Generated typer config parameter callback.

        Args:
            ctx (typer.Context): typer context (automatically passed)
            param (typer.CallbackParam): typer callback parameter (automatically passed)
            param_value (TyperParameterValue): parameter value passed to typer
                (automatically passed)

        Raises:
            BadParameter: bad parameter value

        Returns:
            TyperParameterValue: must return back the given parameter
        """
        try:
            conf = loader(param_value)  # Load config file
            ctx.default_map = ctx.default_map or {}  # Initialize the default map
            ctx.default_map.update(conf)  # Merge the config Dict into default_map
        except Exception as ex:
            raise BadParameter(str(ex), ctx=ctx, param=param) from ex
        return param_value

    return _callback

__typing

Data and Function types.

TyperParameterName module-attribute

TyperParameterName: TypeAlias = str

Typer CLI parameter name.

TyperParameterValue module-attribute

TyperParameterValue: TypeAlias = Any

Typer CLI parameter value.

ConfigDict module-attribute

ConfigDict: TypeAlias = Dict[TyperParameterName, Any]

Configuration dictionary to be applied to the click context default map.

ConfigDictAccessorPath module-attribute

ConfigDictAccessorPath: TypeAlias = Iterable[str]

Configuration dictionary accessor path.

TyperParameterValueTransformer module-attribute

TyperParameterValueTransformer: TypeAlias = Callable[
    [TyperParameterValue], TyperParameterValue
]

Typer parameter value transforming function.

ConfigDictTransformer module-attribute

ConfigDictTransformer: TypeAlias = Callable[
    [ConfigDict], ConfigDict
]

ConfigDict transforming function.

ConfigLoader module-attribute

ConfigLoader: TypeAlias = Callable[
    [TyperParameterValue], ConfigDict
]

Configuration loader function.

ConfigLoaderConditional module-attribute

ConfigLoaderConditional: TypeAlias = Callable[
    [TyperParameterValue], bool
]

Configuration loader conditional function.

ConfigParameterCallback module-attribute

ConfigParameterCallback: TypeAlias = Callable[
    [Context, CallbackParam, TyperParameterValue],
    TyperParameterValue,
]

Typer config parameter callback function.

NoArgCallable module-attribute

NoArgCallable: TypeAlias = Callable[[], Any]

No argument callable.

loaders

Configuration File Loaders.

These loaders must implement the typer_config.__typing.ConfigLoader interface.

loader_transformer

loader_transformer(
    loader: ConfigLoader,
    loader_conditional: Optional[
        ConfigLoaderConditional
    ] = None,
    param_transformer: Optional[
        TyperParameterValueTransformer
    ] = None,
    config_transformer: Optional[
        ConfigDictTransformer
    ] = None,
) -> ConfigLoader

Configuration loader transformer.

This allows to transform the input and output of a configuration loader.

Examples:

Set a default file to open when none is given:

default_file_loader = loader_transformer(
    yaml_loader,
    param_transformer=lambda param: param if param else "config.yml",
)

Use a subsection of a file:

subsection_loader = loader_transformer(
    yaml_loader,
    config_transformer = lambda config: config["subsection"],
)

Use both transformers to use the [tool.my_tool] section from pyproject.toml by default:

pyproject_loader = loader_transformer(
    toml_loader,
    param_transformer = lambda param: param if param else "pyproject.toml"
    config_transformer = lambda config: config["tool"]["my_tool"],
)

Parameters:

Name Type Description Default
loader ConfigLoader

Loader to transform.

required
loader_condtional Optional[ConfigLoaderConditional]

Function to determine whether to execute loader. Defaults to None (no-op).

required
param_transformer Optional[TyperParameterValueTransformer]

Typer parameter transformer. Defaults to None (no-op).

None
config_transformer Optional[ConfigDictTransformer]

Config dictionary transformer. Defaults to None (no-op).

None

Returns:

Name Type Description
ConfigLoader ConfigLoader

Transformed config loader.

Source code in typer_config/loaders.py
 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
125
126
127
128
def loader_transformer(
    loader: ConfigLoader,
    loader_conditional: Optional[ConfigLoaderConditional] = None,
    param_transformer: Optional[TyperParameterValueTransformer] = None,
    config_transformer: Optional[ConfigDictTransformer] = None,
) -> ConfigLoader:
    """Configuration loader transformer.

    This allows to transform the input and output of a configuration loader.

    Examples:
        Set a default file to open when none is given:
        ```py
        default_file_loader = loader_transformer(
            yaml_loader,
            param_transformer=lambda param: param if param else "config.yml",
        )
        ```

        Use a subsection of a file:
        ```py
        subsection_loader = loader_transformer(
            yaml_loader,
            config_transformer = lambda config: config["subsection"],
        )
        ```

        Use both transformers to use the `[tool.my_tool]` section from `pyproject.toml`
        by default:
        ```py
        pyproject_loader = loader_transformer(
            toml_loader,
            param_transformer = lambda param: param if param else "pyproject.toml"
            config_transformer = lambda config: config["tool"]["my_tool"],
        )
        ```

    Args:
        loader (ConfigLoader): Loader to transform.
        loader_condtional (Optional[ConfigLoaderConditional], optional): Function
            to determine whether to execute loader. Defaults to None (no-op).
        param_transformer (Optional[TyperParameterValueTransformer], optional): Typer
            parameter transformer. Defaults to None (no-op).
        config_transformer (Optional[ConfigDictTransformer], optional): Config
            dictionary transformer. Defaults to None (no-op).

    Returns:
        ConfigLoader: Transformed config loader.
    """

    def _loader(param_value: TyperParameterValue) -> ConfigDict:
        # Transform input
        if param_transformer is not None:
            param_value = param_transformer(param_value)

        # Decide whether to execute loader
        # NOTE: bad things can happen when `param_value=''`
        # such as `--help` not working
        conf: ConfigDict = {}
        if loader_conditional is None or loader_conditional(param_value):
            conf = loader(param_value)

        # Transform output
        if config_transformer is not None:
            conf = config_transformer(conf)

        return conf

    return _loader

subpath_loader

subpath_loader(
    loader: ConfigLoader, dictpath: ConfigDictAccessorPath
) -> ConfigLoader

Modify a loader to return a subpath of the dictionary from file.

Warns:

Type Description
DeprecationWarning

This function is deprecated. Please use typer_config.loaders.loader_transformer instead.

Examples:

The following example reads the values from the my_app section in a YAML file structured like this:

tools:
    my_app:
        ... # use these values
    others: # ignore
stuff: # ignore

my_loader = subpath_loader(yaml_loader, ["tools", "my_app"])

Parameters:

Name Type Description Default
loader ConfigLoader

loader to modify

required
dictpath ConfigDictAccessorPath

path to the section of dictionary

required

Returns:

Name Type Description
ConfigLoader ConfigLoader

sub dictionary loader

Source code in typer_config/loaders.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def subpath_loader(
    loader: ConfigLoader, dictpath: ConfigDictAccessorPath
) -> ConfigLoader:
    """Modify a loader to return a subpath of the dictionary from file.

    Warns:
        DeprecationWarning: This function is deprecated. Please use
            typer_config.loaders.loader_transformer instead.

    Examples:
        The following example reads the values from the `my_app` section in
        a YAML file structured like this:
        ```yaml
        tools:
            my_app:
                ... # use these values
            others: # ignore
        stuff: # ignore
        ```

        ```py
        my_loader = subpath_loader(yaml_loader, ["tools", "my_app"])
        ```

    Args:
        loader (ConfigLoader): loader to modify
        dictpath (ConfigDictAccessorPath): path to the section of dictionary

    Returns:
        ConfigLoader: sub dictionary loader
    """

    warn(
        "typer_config.loaders.subpath_loader is deprecated. "
        "Please use typer_config.loaders.loader_transformer instead.",
        DeprecationWarning,
    )

    def _loader(param_value: str) -> ConfigDict:
        # get original ConfigDict
        conf: ConfigDict = loader(param_value)

        # get subpath of dictionary
        for path in dictpath:
            conf = conf.get(path, {})
        return conf

    return _loader

default_value_loader

default_value_loader(
    loader: ConfigLoader, value_getter: NoArgCallable
) -> ConfigLoader

Modify a loader to use a default value if the passed value is false-ish.

Warns:

Type Description
DeprecationWarning

This function is deprecated. Please use typer_config.loaders.loader_transformer instead.

Examples:

The following example lets a user specify a config file, but will load the pyproject.toml if they don't.

pyproject_loader = default_value_loader(toml_loader, lambda: "pyproject.toml")

Parameters:

Name Type Description Default
loader ConfigLoader

loader to modify

required
value_getter NoArgCallable

function that returns default value

required

Returns:

Name Type Description
ConfigLoader ConfigLoader

modified loader

Source code in typer_config/loaders.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def default_value_loader(
    loader: ConfigLoader, value_getter: NoArgCallable
) -> ConfigLoader:
    """Modify a loader to use a default value if the passed value is false-ish.

    Warns:
        DeprecationWarning: This function is deprecated. Please use
            typer_config.loaders.loader_transformer instead.

    Examples:
        The following example lets a user specify a config file, but will load
        the `pyproject.toml` if they don't.

        ```py
        pyproject_loader = default_value_loader(toml_loader, lambda: "pyproject.toml")
        ```

    Args:
        loader (ConfigLoader): loader to modify
        value_getter (NoArgCallable): function that returns default value



    Returns:
        ConfigLoader: modified loader
    """

    warn(
        "typer_config.loaders.default_value_loader is deprecated. "
        "Please use typer_config.loaders.loader_transformer instead.",
        DeprecationWarning,
    )

    def _loader(param_value: str) -> ConfigDict:
        # parameter value was not specified by user
        if not param_value:
            param_value = value_getter()

        conf: ConfigDict = loader(param_value)

        return conf

    return _loader

yaml_loader

yaml_loader(param_value: TyperParameterValue) -> ConfigDict

YAML file loader.

Parameters:

Name Type Description Default
param_value TyperParameterValue

path of YAML file

required

Raises:

Type Description
ModuleNotFoundError

pyyaml library is not installed

Returns:

Name Type Description
ConfigDict ConfigDict

dictionary loaded from file

Source code in typer_config/loaders.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def yaml_loader(param_value: TyperParameterValue) -> ConfigDict:
    """YAML file loader.

    Args:
        param_value (TyperParameterValue): path of YAML file

    Raises:
        ModuleNotFoundError: pyyaml library is not installed

    Returns:
        ConfigDict: dictionary loaded from file
    """

    if YAML_MISSING:  # pragma: no cover
        raise ModuleNotFoundError("Please install the pyyaml library.")

    with open(param_value, "r", encoding="utf-8") as _file:
        conf: ConfigDict = yaml.safe_load(_file)

    return conf

json_loader

json_loader(param_value: TyperParameterValue) -> ConfigDict

JSON file loader.

Parameters:

Name Type Description Default
param_value TyperParameterValue

path of JSON file

required

Returns:

Name Type Description
ConfigDict ConfigDict

dictionary loaded from file

Source code in typer_config/loaders.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def json_loader(param_value: TyperParameterValue) -> ConfigDict:
    """JSON file loader.

    Args:
        param_value (TyperParameterValue): path of JSON file

    Returns:
        ConfigDict: dictionary loaded from file
    """

    with open(param_value, "r", encoding="utf-8") as _file:
        conf: ConfigDict = json.load(_file)

    return conf

toml_loader

toml_loader(param_value: TyperParameterValue) -> ConfigDict

TOML file loader.

Parameters:

Name Type Description Default
param_value TyperParameterValue

path of TOML file

required

Raises:

Type Description
ModuleNotFoundError

toml library is not installed

Returns:

Name Type Description
ConfigDict ConfigDict

dictionary loaded from file

Source code in typer_config/loaders.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def toml_loader(param_value: TyperParameterValue) -> ConfigDict:
    """TOML file loader.

    Args:
        param_value (TyperParameterValue): path of TOML file

    Raises:
        ModuleNotFoundError: toml library is not installed

    Returns:
        ConfigDict: dictionary loaded from file
    """

    if TOML_MISSING:  # pragma: no cover
        raise ModuleNotFoundError("Please install the toml library.")

    conf: ConfigDict = {}

    if USING_TOMLLIB:  # pragma: no cover
        with open(param_value, "rb") as _file:
            conf = tomllib.load(_file)  # type: ignore
    else:  # pragma: no cover
        with open(param_value, "r", encoding="utf-8") as _file:
            conf = toml.load(_file)  # type: ignore

    return conf

dotenv_loader

dotenv_loader(
    param_value: TyperParameterValue,
) -> ConfigDict

Dotenv file loader.

Parameters:

Name Type Description Default
param_value TyperParameterValue

path of Dotenv file

required

Raises:

Type Description
ModuleNotFoundError

python-dotenv library is not installed

Returns:

Name Type Description
ConfigDict ConfigDict

dictionary loaded from file

Source code in typer_config/loaders.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def dotenv_loader(param_value: TyperParameterValue) -> ConfigDict:
    """Dotenv file loader.

    Args:
        param_value (TyperParameterValue): path of Dotenv file

    Raises:
        ModuleNotFoundError: python-dotenv library is not installed

    Returns:
        ConfigDict: dictionary loaded from file
    """

    if DOTENV_MISSING:  # pragma: no cover
        raise ModuleNotFoundError("Please install the python-dotenv library.")

    with open(param_value, "r", encoding="utf-8") as _file:
        # NOTE: I'm using a stream here so that the loader
        # will raise an exception when the file doesn't exist.
        conf: ConfigDict = dotenv.dotenv_values(stream=_file)

    return conf

ini_loader

ini_loader(param_value: TyperParameterValue) -> ConfigDict

INI file loader

Note

INI files must have sections at the top level. You probably want to combine this with subpath_loader. For example:

ini_section_loader = subpath_loader(ini_loader, ["section"])

Parameters:

Name Type Description Default
param_value TyperParameterValue

path of INI file

required

Returns:

Name Type Description
ConfigDict ConfigDict

dictionary loaded from file

Source code in typer_config/loaders.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def ini_loader(param_value: TyperParameterValue) -> ConfigDict:
    """INI file loader

    Note:
        INI files must have sections at the top level.
        You probably want to combine this with `subpath_loader`.
        For example:
        ```py
        ini_section_loader = subpath_loader(ini_loader, ["section"])
        ```

    Args:
        param_value (TyperParameterValue): path of INI file

    Returns:
        ConfigDict: dictionary loaded from file
    """

    ini_parser = ConfigParser()
    with open(param_value, "r", encoding="utf-8") as _file:
        ini_parser.read_file(_file)

    conf: ConfigDict = {
        sect: dict(ini_parser.items(sect)) for sect in ini_parser.sections()
    }

    return conf