Last active
September 26, 2024 14:34
-
-
Save YouJiacheng/7c95758076c936cf360b5125f26ee263 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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