Skip to content

Instantly share code, notes, and snippets.

@apua
Last active November 6, 2024 13:49
Show Gist options
  • Save apua/d701fd631fd25e46cd543a1696c90528 to your computer and use it in GitHub Desktop.
Save apua/d701fd631fd25e46cd543a1696c90528 to your computer and use it in GitHub Desktop.
r"""
>>> f('''
... [variables]
... c = 1
... d.e = 1
... f = ['{g}']
... g = ['{gg}']
... gg = 1
...
... [a]
... b = 1
... ''')
{'c': 1, 'd': {'e': 1}, 'f': [[1]], 'g': [1], 'gg': 1}
"""
def f(s):
import re
import tomli as tomllib
raw_config = tomllib.loads(s)
variables = raw_config.get('variables', {})
def expand(data, base=None):
if base is None:
base = data
match data:
case str():
if m := re.search(r'^{(.*)}$', data):
return expand(eval(m.group(1), None, base), base)
else:
return data
case dict():
return {k: expand(v, base) for k, v in data.items()}
case list():
return [expand(v, base) for v in data]
case _:
return data
return expand(variables)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment