I have a toml file that looks like
[default]
conf_path = "d"
prefix = "p"
suffix = "s"
I am turning this into a dict that looks like,
{default: {'conf_path': 'd', 'prefix': 'p', 'suffix': 's'}}
They key is default
and the value is a dictionary. I want to check if default
exists and for the dict in the value -- I want to check that the conf_path, prefix, suffix keys exist and that they all have a value that isn't ''
or None
.
This is what I have so far. I am having trouble checking the keys and values in default's value dict.
def get_config_path() -> str:
"""
"""
default_path = os.path.expanduser(const.CONFIG_PATH)
final_path = os.environ.get('CONFIG_PATH', default_path)
return final_path
def check_toml():
conf = Path(get_config_path())
default_table = ['default', 'conf_path', 'prefix', 'suffix']
if conf.exists():
toml_dict = tomlkit.loads(Path(get_config_path()).read_text())
d = toml_dict['default']
for key, value in d.items():
d = key
else: d = 'File does not exist.'
return d
How can I check that the three specific keys exist and they each have a value?
I don't know how to check that all three keys exist, they all have a value that isn't ''
or None
, and then say true if all of that is met.
I can do one no prob though
if toml_dict['default'].get('conf_path') not in (None, ''):
I was thinking use a list some how.
CodePudding user response:
if 'default' in conf and all(key in conf['default'] and conf['default'][key] for key in ('conf_path', 'prefix', 'suffix')):
This makes sure that the default
element exists, and that each of the keys you're interested in has a Truthy value (I.E. not None or '').
CodePudding user response:
Open the toml file for reading and build your dictionary with tomlkit.
Then check for expected values like this:
import tomlkit
with open('foo.toml') as toml:
_dict = tomlkit.loads(toml.read())
if dd := _dict.get('default'):
for key in 'conf_path', 'prefix', 'suffix':
if not dd.get(key):
print(f'Expected key "{key}" is missing')
else:
print('Missing default section')