Skip to content

Instantly share code, notes, and snippets.

@YouJiacheng
Last active September 26, 2024 14:34
Show Gist options
  • Save YouJiacheng/7c95758076c936cf360b5125f26ee263 to your computer and use it in GitHub Desktop.
Save YouJiacheng/7c95758076c936cf360b5125f26ee263 to your computer and use it in GitHub Desktop.
from dataclasses import dataclass
class Default(dict[str, str]):
def __missing__(self, key: str):
return f"{{{key}}}"
@dataclass
class Pair:
key: str
value: str
def __format__(self, format_spec: str):
if format_spec == "":
return self.value
return format_spec.format_map(Default({self.key: self.value}))
template = "{x} {y}{z}"
x = Pair("x", "hello")
y = Pair("y", "world")
z = Pair("z", "foo")
layer_1_format = "{x:{template}}".format(x=x, template=template)
layer_1_format = "{y:{layer_1_format}}".format(y=y, layer_1_format=layer_1_format)
layer_1_fstr = f"{x:{template}}"
layer_1_fstr = f"{y:{layer_1_fstr}}"
# 3.11 - SyntaxError: f-string: expressions nested too deeply
layer_2_fstr = f"{x:{y:{template}}}"
# ValueError: Max string recursion exceeded
# layer_2_format = "{x:{y:{template}}}".format(x=x, y=y, template=template)
assert layer_1_format == layer_1_fstr == layer_2_fstr == "hello world{z}"
# SyntaxError: f-string: expressions nested too deeply
# layer_3_fstr = f"{x:{y:{z:{template}}}}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment