Skip to content

typer_config

Typer Configuration Utilities.

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 Context

typer context (automatically passed)

required
param 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 Context

typer context (automatically passed)

required
param 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 Context

typer context (automatically passed)

required
param 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

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 Context

typer context (automatically passed)

required
param 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/callbacks.py
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
55
56
57
58
59
60
61
62
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

use_config

use_config(
    callback: ConfigParameterCallback,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
) -> TyperCommandDecorator

Decorator for using configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_config
from typer_config import yaml_conf_callback # whichever callback to use

app = typer.Typer()

@app.command()
@use_config(yaml_conf_callback)
def main(...):
    ...

Parameters:

Name Type Description Default
callback ConfigParameterCallback

config parameter callback to load

required
param_name TyperParameterName

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
 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
def use_config(
    callback: ConfigParameterCallback,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
) -> TyperCommandDecorator:
    """Decorator for using configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_config
        from typer_config import yaml_conf_callback # whichever callback to use

        app = typer.Typer()

        @app.command()
        @use_config(yaml_conf_callback)
        def main(...):
            ...
        ```

    Args:
        callback (ConfigParameterCallback): config parameter callback to load
        param_name (TyperParameterName, optional): name of config parameter.
            Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    def decorator(cmd: TyperCommand) -> TyperCommand:
        # NOTE: modifying a function's __signature__ is dangerous
        # in the sense that it only affects inspect.signature().
        # It does not affect the actual function implementation.
        # So, a caller can be confused how to pass parameters to
        # the function with modified signature.
        if sys.version_info < (3, 10):
            sig = signature(cmd)
        else:
            sig = signature(cmd, eval_str=True)

        config_param = Parameter(
            param_name,
            kind=Parameter.KEYWORD_ONLY,
            annotation=str,
            default=Option("", callback=callback, is_eager=True, help=param_help),
        )

        new_sig = sig.replace(parameters=[*sig.parameters.values(), config_param])

        @wraps(cmd)
        def wrapped(*args, **kwargs):  # noqa: ANN202,ANN002,ANN003
            # NOTE: need to delete the config parameter
            # to match the wrapped command's signature.
            if param_name in kwargs:
                del kwargs[param_name]

            return cmd(*args, **kwargs)

        wrapped.__signature__ = new_sig  # type: ignore

        return wrapped

    return decorator

use_ini_config

use_ini_config(
    section: List[str],
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using INI configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_ini_config

app = typer.Typer()

@app.command()
@use_ini_config(["section", "subsection"])
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the INI file.

required
param_name str

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
315
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def use_ini_config(
    section: List[str],
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using INI configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_ini_config

        app = typer.Typer()

        @app.command()
        @use_ini_config(["section", "subsection"])
        def main(...):
            ...
        ```

    Args:
        section (List[str]): List of nested sections to access in the INI file.
        param_name (str, optional): name of config parameter. Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            ini_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

use_json_config

use_json_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using JSON configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_json_config

app = typer.Typer()

@app.command()
@use_json_config()
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the config. Defaults to None.

None
param_name TyperParameterName

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
def use_json_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using JSON configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_json_config

        app = typer.Typer()

        @app.command()
        @use_json_config()
        def main(...):
            ...
        ```

    Args:
        section (List[str], optional): List of nested sections to access in the config.
            Defaults to None.
        param_name (TyperParameterName, optional): name of config parameter.
            Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            json_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

use_toml_config

use_toml_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using TOML configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_toml_config

app = typer.Typer()

@app.command()
@use_toml_config()
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the config. Defaults to None.

None
param_name str

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def use_toml_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using TOML configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_toml_config

        app = typer.Typer()

        @app.command()
        @use_toml_config()
        def main(...):
            ...
        ```

    Args:
        section (List[str], optional): List of nested sections to access in the config.
            Defaults to None.
        param_name (str, optional): name of config parameter. Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            toml_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

use_yaml_config

use_yaml_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using YAML configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_yaml_config

app = typer.Typer()

@app.command()
@use_yaml_config()
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the config. Defaults to None.

None
param_name str

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
def use_yaml_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using YAML configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_yaml_config

        app = typer.Typer()

        @app.command()
        @use_yaml_config()
        def main(...):
            ...
        ```

    Args:
        section (List[str], optional): List of nested sections to access in the config.
            Defaults to None.
        param_name (str, optional): name of config parameter. Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            yaml_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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
    """

    dotenv = try_import("dotenv")

    if dotenv is None:  # pragma: no cover
        message = "Please install the python-dotenv library."
        raise ModuleNotFoundError(message)

    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 loader_transformer to extract the correct section. For example:

ini_section_loader = loader_transformer(
    ini_loader,
    config_transformer=lambda config: config["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
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
224
225
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 `loader_transformer`
        to extract the correct section.
        For example:
        ```py
        ini_section_loader = loader_transformer(
            ini_loader,
            config_transformer=lambda config: config["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

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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
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
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
    """

    # try `tomllib` first
    tomllib = try_import("tomllib")

    if tomllib is not None:
        with open(param_value, "rb") as _file:
            return tomllib.load(_file)

    # couldn't find `tommllib`, so try `toml`
    toml = try_import("toml")

    if toml is None:  # pragma: no cover
        message = "Please install the toml library."
        raise ModuleNotFoundError(message)

    with open(param_value, "r", encoding="utf-8") as _file:
        return toml.load(_file)

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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
    """

    yaml = try_import("yaml")

    if yaml is None:  # pragma: no cover
        message = "Please install the pyyaml library."
        raise ModuleNotFoundError(message)

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

    return conf

__optional_imports

Handle optional imports.

try_import cached

try_import(module_name: str)

Try to import a module by name.

Note: caches the imported modules in a functools.lru_cache

Parameters:

Name Type Description Default
module_name str

name of module to import

required

Returns:

Name Type Description
Module

imported module

Source code in typer_config/__optional_imports.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
@lru_cache()
def try_import(module_name: str):  # noqa: ANN202 (no type for modules)
    """Try to import a module by name.

    Note: caches the imported modules in a `functools.lru_cache`

    Args:
        module_name (str): name of module to import

    Returns:
        Module: imported module
    """
    if find_spec(module_name):
        return import_module(module_name)
    return None

__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

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

FilePath module-attribute

FilePath: TypeAlias = Union[Path, str]

File 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

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.

ConfigDumper module-attribute

ConfigDumper: TypeAlias = Callable[
    [ConfigDict, FilePath], None
]

Configuration dumper function.

TyperCommand module-attribute

TyperCommand: TypeAlias = Callable[..., Any]

A function that will be decorated with typer.Typer().command().

TyperCommandDecorator module-attribute

TyperCommandDecorator: TypeAlias = Callable[
    [TyperCommand], TyperCommand
]

A decorator applied to a typer command.

callbacks

Typer Configuration Parameter Callbacks.

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 Context

typer context (automatically passed)

required
param 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 Context

typer context (automatically passed)

required
param 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 Context

typer context (automatically passed)

required
param 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 Context

typer context (automatically passed)

required
param 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/callbacks.py
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
55
56
57
58
59
60
61
62
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

argument_list_callback

argument_list_callback(
    ctx: Context,
    param: CallbackParam,
    param_value: Optional[List[str]],
) -> List[str]

Argument list callback.

Note

This is a shim to fix list arguments in a config. See maxb2/typer-config#124.

Parameters:

Name Type Description Default
ctx Context

typer context

required
param CallbackParam

typer parameter

required
param_value Optional[List[str]]

typer parameter value

required

Returns:

Type Description
List[str]

List[str]: argument list

Source code in typer_config/callbacks.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def argument_list_callback(
    ctx: Context, param: CallbackParam, param_value: Optional[List[str]]
) -> List[str]:
    """Argument list callback.

    Note:
        This is a shim to fix list arguments in a config.
        See [maxb2/typer-config#124](https://github.com/maxb2/typer-config/issues/124).

    Args:
        ctx (typer.Context): typer context
        param (typer.CallbackParam): typer parameter
        param_value (Optional[List[str]]): typer parameter value

    Returns:
        List[str]: argument list
    """
    ctx.default_map = ctx.default_map or {}
    default = ctx.default_map.get(param.name, []) if param.name else []
    return param_value if param_value else default

decorators

Typer Config decorators.

use_config

use_config(
    callback: ConfigParameterCallback,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
) -> TyperCommandDecorator

Decorator for using configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_config
from typer_config import yaml_conf_callback # whichever callback to use

app = typer.Typer()

@app.command()
@use_config(yaml_conf_callback)
def main(...):
    ...

Parameters:

Name Type Description Default
callback ConfigParameterCallback

config parameter callback to load

required
param_name TyperParameterName

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
 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
def use_config(
    callback: ConfigParameterCallback,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
) -> TyperCommandDecorator:
    """Decorator for using configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_config
        from typer_config import yaml_conf_callback # whichever callback to use

        app = typer.Typer()

        @app.command()
        @use_config(yaml_conf_callback)
        def main(...):
            ...
        ```

    Args:
        callback (ConfigParameterCallback): config parameter callback to load
        param_name (TyperParameterName, optional): name of config parameter.
            Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    def decorator(cmd: TyperCommand) -> TyperCommand:
        # NOTE: modifying a function's __signature__ is dangerous
        # in the sense that it only affects inspect.signature().
        # It does not affect the actual function implementation.
        # So, a caller can be confused how to pass parameters to
        # the function with modified signature.
        if sys.version_info < (3, 10):
            sig = signature(cmd)
        else:
            sig = signature(cmd, eval_str=True)

        config_param = Parameter(
            param_name,
            kind=Parameter.KEYWORD_ONLY,
            annotation=str,
            default=Option("", callback=callback, is_eager=True, help=param_help),
        )

        new_sig = sig.replace(parameters=[*sig.parameters.values(), config_param])

        @wraps(cmd)
        def wrapped(*args, **kwargs):  # noqa: ANN202,ANN002,ANN003
            # NOTE: need to delete the config parameter
            # to match the wrapped command's signature.
            if param_name in kwargs:
                del kwargs[param_name]

            return cmd(*args, **kwargs)

        wrapped.__signature__ = new_sig  # type: ignore

        return wrapped

    return decorator

use_json_config

use_json_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using JSON configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_json_config

app = typer.Typer()

@app.command()
@use_json_config()
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the config. Defaults to None.

None
param_name TyperParameterName

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
def use_json_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using JSON configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_json_config

        app = typer.Typer()

        @app.command()
        @use_json_config()
        def main(...):
            ...
        ```

    Args:
        section (List[str], optional): List of nested sections to access in the config.
            Defaults to None.
        param_name (TyperParameterName, optional): name of config parameter.
            Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            json_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

use_yaml_config

use_yaml_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using YAML configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_yaml_config

app = typer.Typer()

@app.command()
@use_yaml_config()
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the config. Defaults to None.

None
param_name str

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
def use_yaml_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using YAML configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_yaml_config

        app = typer.Typer()

        @app.command()
        @use_yaml_config()
        def main(...):
            ...
        ```

    Args:
        section (List[str], optional): List of nested sections to access in the config.
            Defaults to None.
        param_name (str, optional): name of config parameter. Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            yaml_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

use_toml_config

use_toml_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using TOML configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_toml_config

app = typer.Typer()

@app.command()
@use_toml_config()
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the config. Defaults to None.

None
param_name str

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def use_toml_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using TOML configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_toml_config

        app = typer.Typer()

        @app.command()
        @use_toml_config()
        def main(...):
            ...
        ```

    Args:
        section (List[str], optional): List of nested sections to access in the config.
            Defaults to None.
        param_name (str, optional): name of config parameter. Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            toml_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

use_dotenv_config

use_dotenv_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using dotenv configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_dotenv_config

app = typer.Typer()

@app.command()
@use_dotenv_config()
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the config. Defaults to None.

None
param_name str

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
263
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def use_dotenv_config(
    section: Optional[List[str]] = None,
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using dotenv configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_dotenv_config

        app = typer.Typer()

        @app.command()
        @use_dotenv_config()
        def main(...):
            ...
        ```

    Args:
        section (List[str], optional): List of nested sections to access in the config.
            Defaults to None.
        param_name (str, optional): name of config parameter. Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            dotenv_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

use_ini_config

use_ini_config(
    section: List[str],
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator

Decorator for using INI configuration on a typer command.

Usage
import typer
from typer_config.decorators import use_ini_config

app = typer.Typer()

@app.command()
@use_ini_config(["section", "subsection"])
def main(...):
    ...

Parameters:

Name Type Description Default
section List[str]

List of nested sections to access in the INI file.

required
param_name str

name of config parameter. Defaults to "config".

'config'
param_help str

config parameter help string. Defaults to "Configuration file.".

'Configuration file.'
default_value TyperParameterValue

default config parameter value. Defaults to None.

None

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

decorator to apply to command

Source code in typer_config/decorators.py
315
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def use_ini_config(
    section: List[str],
    param_name: TyperParameterName = "config",
    param_help: str = "Configuration file.",
    default_value: Optional[TyperParameterValue] = None,
) -> TyperCommandDecorator:
    """Decorator for using INI configuration on a typer command.

    Usage:
        ```py
        import typer
        from typer_config.decorators import use_ini_config

        app = typer.Typer()

        @app.command()
        @use_ini_config(["section", "subsection"])
        def main(...):
            ...
        ```

    Args:
        section (List[str]): List of nested sections to access in the INI file.
        param_name (str, optional): name of config parameter. Defaults to "config".
        param_help (str, optional): config parameter help string.
            Defaults to "Configuration file.".
        default_value (TyperParameterValue, optional): default config parameter value.
            Defaults to None.

    Returns:
        TyperCommandDecorator: decorator to apply to command
    """

    callback = conf_callback_factory(
        loader_transformer(
            ini_loader,
            loader_conditional=lambda param_value: (
                file_exists_and_warn(param_value) if param_value else param_value
            ),
            param_transformer=(
                (lambda param_value: param_value if param_value else default_value)
                if default_value is not None
                else None
            ),
            config_transformer=lambda config: get_dict_section(config, section),
        )
    )

    return use_config(callback=callback, param_name=param_name, param_help=param_help)

dump_config

dump_config(
    dumper: ConfigDumper, location: FilePath
) -> TyperCommandDecorator

Decorator for dumping a config file with parameters from an invocation of a typer command.

Usage
import typer
from typer.decorators import dump_config

app = typer.Typer()

@app.command()
# NOTE: @dump_config MUST BE AFTER @app.command()
@dump_config(yaml_dumper, "config_dump_dir/params.yaml")
def cmd(...):
    ...

Parameters:

Name Type Description Default
dumper ConfigDumper

config file dumper

required
location FilePath

config file to write

required

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

command decorator

Source code in typer_config/decorators.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def dump_config(dumper: ConfigDumper, location: FilePath) -> TyperCommandDecorator:
    """Decorator for dumping a config file with parameters
    from an invocation of a typer command.

    Usage:
        ```py
        import typer
        from typer.decorators import dump_config

        app = typer.Typer()

        @app.command()
        # NOTE: @dump_config MUST BE AFTER @app.command()
        @dump_config(yaml_dumper, "config_dump_dir/params.yaml")
        def cmd(...):
            ...
        ```

    Args:
        dumper (ConfigDumper): config file dumper
        location (FilePath): config file to write

    Returns:
        TyperCommandDecorator: command decorator
    """

    def decorator(cmd: TyperCommand) -> TyperCommand:
        @wraps(cmd)
        def inner(*args, **kwargs):  # noqa: ANN202,ANN002,ANN003
            # get a dictionary of the passed args
            bound_args = signature(cmd).bind(*args, **kwargs).arguments

            # convert enums to their values
            # NOTE: bound_args shouldn't be nested in the typer
            # framework, so top level iteration should be fine.
            for key, val in bound_args.items():
                if isinstance(val, Enum):
                    bound_args[key] = val.value

            # dump passed args
            dumper(bound_args, location)

            # run original command
            return cmd(*args, **kwargs)

        return inner

    return decorator

dump_json_config

dump_json_config(
    location: FilePath,
) -> TyperCommandDecorator

Decorator for dumping a JSON file with parameters from an invocation of a typer command.

Usage
import typer
from typer.decorators import dump_json_config

app = typer.Typer()

@app.command()
# NOTE: @dump_json_config MUST BE AFTER @app.command()
@dump_json_config("config_dump_dir/params.json")
def cmd(...):
    ...

Parameters:

Name Type Description Default
location FilePath

config file to write

required

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

command decorator

Source code in typer_config/decorators.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def dump_json_config(location: FilePath) -> TyperCommandDecorator:
    """Decorator for dumping a JSON file with parameters
    from an invocation of a typer command.

    Usage:
        ```py
        import typer
        from typer.decorators import dump_json_config

        app = typer.Typer()

        @app.command()
        # NOTE: @dump_json_config MUST BE AFTER @app.command()
        @dump_json_config("config_dump_dir/params.json")
        def cmd(...):
            ...
        ```

    Args:
        location (FilePath): config file to write

    Returns:
        TyperCommandDecorator: command decorator
    """
    return dump_config(dumper=json_dumper, location=location)

dump_yaml_config

dump_yaml_config(
    location: FilePath,
) -> TyperCommandDecorator

Decorator for dumping a YAML file with parameters from an invocation of a typer command.

Usage
import typer
from typer.decorators import dump_yaml_config

app = typer.Typer()

@app.command()
# NOTE: @dump_yaml_config MUST BE AFTER @app.command()
@dump_yaml_config("config_dump_dir/params.yml")
def cmd(...):
    ...

Parameters:

Name Type Description Default
location FilePath

config file to write

required

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

command decorator

Source code in typer_config/decorators.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def dump_yaml_config(location: FilePath) -> TyperCommandDecorator:
    """Decorator for dumping a YAML file with parameters
    from an invocation of a typer command.

    Usage:
        ```py
        import typer
        from typer.decorators import dump_yaml_config

        app = typer.Typer()

        @app.command()
        # NOTE: @dump_yaml_config MUST BE AFTER @app.command()
        @dump_yaml_config("config_dump_dir/params.yml")
        def cmd(...):
            ...
        ```

    Args:
        location (FilePath): config file to write

    Returns:
        TyperCommandDecorator: command decorator
    """
    return dump_config(dumper=yaml_dumper, location=location)

dump_toml_config

dump_toml_config(
    location: FilePath,
) -> TyperCommandDecorator

Decorator for dumping a TOML file with parameters from an invocation of a typer command.

Usage
import typer
from typer.decorators import dump_toml_config

app = typer.Typer()

@app.command()
# NOTE: @dump_toml_config MUST BE AFTER @app.command()
@dump_toml_config("config_dump_dir/params.toml")
def cmd(...):
    ...

Parameters:

Name Type Description Default
location FilePath

config file to write

required

Returns:

Name Type Description
TyperCommandDecorator TyperCommandDecorator

command decorator

Source code in typer_config/decorators.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
def dump_toml_config(location: FilePath) -> TyperCommandDecorator:
    """Decorator for dumping a TOML file with parameters
    from an invocation of a typer command.

    Usage:
        ```py
        import typer
        from typer.decorators import dump_toml_config

        app = typer.Typer()

        @app.command()
        # NOTE: @dump_toml_config MUST BE AFTER @app.command()
        @dump_toml_config("config_dump_dir/params.toml")
        def cmd(...):
            ...
        ```

    Args:
        location (FilePath): config file to write

    Returns:
        TyperCommandDecorator: command decorator
    """
    return dump_config(dumper=toml_dumper, location=location)

dumpers

Config Dictionary Dumpers.

json_dumper

json_dumper(config: ConfigDict, location: FilePath) -> None

Dump config to JSON file.

Parameters:

Name Type Description Default
config ConfigDict

configuration

required
location FilePath

file to write

required
Source code in typer_config/dumpers.py
 9
10
11
12
13
14
15
16
17
def json_dumper(config: ConfigDict, location: FilePath) -> None:
    """Dump config to JSON file.

    Args:
        config (ConfigDict): configuration
        location (FilePath): file to write
    """
    with open(location, "w", encoding="utf-8") as _file:
        json.dump(config, _file)

yaml_dumper

yaml_dumper(config: ConfigDict, location: FilePath) -> None

Dump config to YAML file.

Parameters:

Name Type Description Default
config ConfigDict

configuration

required
location FilePath

file to write

required

Raises:

Type Description
ModuleNotFoundError

pyyaml is required

Source code in typer_config/dumpers.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def yaml_dumper(config: ConfigDict, location: FilePath) -> None:
    """Dump config to YAML file.

    Args:
        config (ConfigDict): configuration
        location (FilePath): file to write

    Raises:
        ModuleNotFoundError: pyyaml is required
    """

    yaml = try_import("yaml")

    if yaml is None:  # pragma: no cover
        message = "Please install the pyyaml library."
        raise ModuleNotFoundError(message)

    with open(location, "w", encoding="utf-8") as _file:
        # NOTE: we must convert config from OrderedDict to dict because
        # pyyaml can't load OrderedDict for python <= 3.8
        yaml.dump(dict(config), _file)

toml_dumper

toml_dumper(config: ConfigDict, location: FilePath) -> None

Dump config to TOML file.

Parameters:

Name Type Description Default
config ConfigDict

configuration

required
location FilePath

file to write

required

Raises:

Type Description
ModuleNotFoundError

toml library is required for writing files

Source code in typer_config/dumpers.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def toml_dumper(config: ConfigDict, location: FilePath) -> None:
    """Dump config to TOML file.

    Args:
        config (ConfigDict): configuration
        location (FilePath): file to write

    Raises:
        ModuleNotFoundError: toml library is required for writing files
    """

    toml = try_import("toml")

    if toml is None:  # pragma: no cover
        message = "Please install the toml library to write TOML files."
        raise ModuleNotFoundError(message)

    with open(location, "w", encoding="utf-8") as _file:
        toml.dump(config, _file)  # type: ignore

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_conditional Optional[ConfigLoaderConditional]

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

None
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
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
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
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_conditional (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

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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
    """

    yaml = try_import("yaml")

    if yaml is None:  # pragma: no cover
        message = "Please install the pyyaml library."
        raise ModuleNotFoundError(message)

    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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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
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
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
    """

    # try `tomllib` first
    tomllib = try_import("tomllib")

    if tomllib is not None:
        with open(param_value, "rb") as _file:
            return tomllib.load(_file)

    # couldn't find `tommllib`, so try `toml`
    toml = try_import("toml")

    if toml is None:  # pragma: no cover
        message = "Please install the toml library."
        raise ModuleNotFoundError(message)

    with open(param_value, "r", encoding="utf-8") as _file:
        return toml.load(_file)

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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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
    """

    dotenv = try_import("dotenv")

    if dotenv is None:  # pragma: no cover
        message = "Please install the python-dotenv library."
        raise ModuleNotFoundError(message)

    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 loader_transformer to extract the correct section. For example:

ini_section_loader = loader_transformer(
    ini_loader,
    config_transformer=lambda config: config["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
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
224
225
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 `loader_transformer`
        to extract the correct section.
        For example:
        ```py
        ini_section_loader = loader_transformer(
            ini_loader,
            config_transformer=lambda config: config["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

utils

Utilities.

SimpleWarningFormat

Simple Warning Formatter.

Source code in typer_config/utils.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class SimpleWarningFormat:
    """Simple Warning Formatter."""

    def __enter__(self: SimpleWarningFormat) -> None:  # noqa: D105
        warnings.formatwarning = (
            lambda msg, category, *args, **kwargs: f"{category.__name__}: {msg}\n"  # noqa: ARG005
        )

    def __exit__(  # noqa: D105
        self: SimpleWarningFormat,
        exc_type: Any,  # noqa: ANN401
        exc_value: Any,  # noqa: ANN401
        exc_tb: Any,  # noqa: ANN401
    ) -> None:
        warnings.formatwarning = ORIGINAL_WARNING_FORMATTER

get_dict_section

get_dict_section(
    _dict: Dict[Any, Any], keys: Optional[List[Any]] = None
) -> Dict[Any, Any]

Get section of a dictionary.

Parameters:

Name Type Description Default
_dict Dict[str, Any]

dictionary to access

required
keys List[str]

list of keys to successively access in the dictionary

None

Returns:

Type Description
Dict[Any, Any]

Dict[str, Any]: section of dictionary requested

Source code in typer_config/utils.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def get_dict_section(
    _dict: Dict[Any, Any], keys: Optional[List[Any]] = None
) -> Dict[Any, Any]:
    """Get section of a dictionary.

    Args:
        _dict (Dict[str, Any]): dictionary to access
        keys (List[str]): list of keys to successively access in the dictionary

    Returns:
        Dict[str, Any]: section of dictionary requested
    """
    if keys is not None:
        for key in keys:
            _dict = _dict.get(key, {})

    return _dict

file_exists_and_warn

file_exists_and_warn(file_path: Union[Path, str]) -> bool

Check if file exists and warn if it doesn't exist.

Parameters:

Name Type Description Default
file_path Union[Path, str]

file path to check

required

Returns:

Name Type Description
bool bool

whether file exists

Source code in typer_config/utils.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def file_exists_and_warn(file_path: Union[Path, str]) -> bool:
    """Check if file exists and warn if it doesn't exist.

    Args:
        file_path (Union[Path, str]): file path to check

    Returns:
        bool: whether file exists
    """

    file_path_exists = Path(file_path).is_file()

    if not file_path_exists:
        msg = f"No such file: '{file_path}'"

        with SimpleWarningFormat():
            showwarning(msg, UserWarning, "", 0)

    return file_path_exists