From a9f59822fc63e0f19999d584642f2982a4f777c6 Mon Sep 17 00:00:00 2001 From: dtomlinson Date: Fri, 3 Jan 2020 17:31:13 +0000 Subject: [PATCH] updating config library.py --- .../read-from-config/library.py | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/python/module-packages/read-from-config/library.py b/python/module-packages/read-from-config/library.py index 253919c..ebc50c3 100644 --- a/python/module-packages/read-from-config/library.py +++ b/python/module-packages/read-from-config/library.py @@ -1,7 +1,8 @@ # Change MYMODULE from __future__ import annotations import sys -from typing import Any, TypeVar, Type, TYPE_CHECKING +from typing import Any, TypeVar, Type, TYPE_CHECKING, Union, List +import ast if TYPE_CHECKING: import logging @@ -24,22 +25,54 @@ def set_config( key: str, default: str = None, cast: Any = None, + check: Union[None, List] = None, ) -> None: """Sets the config variable on the instance of a class. Parameters ---------- config_inst : Type[config_inst_t] - Instance of the :class:`~MYMODULE.config.Config` class. + Instance of the :class:`~netacea_slackbot.config.Config` class. key : str The key referencing the config variable. default : str, optional The default value. cast : Any, optional The type of the variable. + check : Union[None, List], optional + Type of object to check against. This is useful if you want to use TOML + to define a list, but want to make sure that a string representation + of a list will be loaded properly if it set as an environment variable. + + Example: + + `config.toml` has the following attribute set: + [package.users] + auth = ['user1', 'user2'] + + If set as an environment variable you can pass this list as a string + and set check=list: + + Environment variable: + PACKAGE_USERS_AUTH = "['user1', 'user2']" + + Usage in code: + ```python + set_config(CONFIG, 'users.auth', check=list) + ``` """ config_var = key.lower().replace('.', '_') - setattr(config_inst, config_var, config_inst.get(key, default, cast)) + if check is None: + setattr(config_inst, config_var, config_inst.get(key, default, cast)) + else: + if type(config_inst.get(key, default, cast)) is not check: + if check is list: + var = ast.literal_eval(config_inst.get(key, default, cast)) + setattr(config_inst, config_var, var) + else: + setattr( + config_inst, config_var, config_inst.get(key, default, cast) + ) # Create function to print cached logged messages and reset