-
Notifications
You must be signed in to change notification settings - Fork 0
/
dstring.py
42 lines (38 loc) · 1.33 KB
/
dstring.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
import io
import ast
import inspect
from dataclasses import dataclass
@dataclass
class Var:
name: str
class DString:
def __init__(self, string, vars):
tree = ast.parse(f"f'{string}'", mode='eval')
self.vars = {}
self.template = []
self.dst_action = None
self.st_mem = False
match tree:
case ast.Expression(body=ast.JoinedStr(values=values)):
for val in values:
match val:
case ast.Constant(value=v):
self.template.append(v)
case ast.FormattedValue(value=ast.Name(id=name)):
self.template.append(Var(name))
self.vars[name] = vars[name]
case _:
raise Exception(f'Unexpected val {val}')
case _:
raise Exception(f'Unexpected tree {tree}')
def __str__(self):
with io.StringIO() as out:
for val in self.template:
match val:
case str(): out.write(val)
case Var(): out.write(str(self.vars[val.name]))
return out.getvalue()
def d(string, dst_action=None):
s = DString(string, inspect.currentframe().f_back.f_locals)
s.dst_action = dst_action
return s