python - 如何推迟/推迟 f 弦的评估?

标签 python python-3.x string-interpolation python-3.6 f-string

我正在使用模板字符串来生成一些文件,我喜欢新的 f 字符串的简洁性,用于减少我以前的模板代码,如下所示:

template_a = "The current name is {name}"
names = ["foo", "bar"]
for name in names:
    print (template_a.format(**locals()))

现在我可以这样做了,直接替换变量:

names = ["foo", "bar"]
for name in names:
    print (f"The current name is {name}")

但是,有时将模板定义在别处是有意义的——在代码的更高层,或者从文件或其他东西中导入。这意味着模板是一个带有格式化标签的静态字符串。字符串必须发生一些事情来告诉解释器将字符串解释为新的 f 字符串,但我不知道是否有这样的事情。

有什么方法可以引入字符串并将其解释为 f 字符串以避免使用 .format(**locals()) 调用?

理想情况下,我希望能够像这样编写代码......(其中 magic_fstring_function 是我不理解的部分):

template_a = f"The current name is {name}"
# OR [Ideal2] template_a = magic_fstring_function(open('template.txt').read())
names = ["foo", "bar"]
for name in names:
    print (template_a)

...具有所需的输出(无需两次读取文件):

The current name is foo
The current name is bar

...但我得到的实际输出是:

The current name is {name}
The current name is {name}

最佳答案

这是一个完整的“理想 2”。

它不是 f 字符串——它甚至不使用 f 字符串——但它按要求使用。完全按照指定的语法。没有安全问题,因为我们没有使用 eval()

它使用了一个小类并实现了 __str__,它会被 print 自动调用。为了摆脱类的有限范围,我们使用 inspect 模块向上跳一帧并查看调用者可以访问的变量。

import inspect

class magic_fstring_function:
    def __init__(self, payload):
        self.payload = payload
    def __str__(self):
        vars = inspect.currentframe().f_back.f_globals.copy()
        vars.update(inspect.currentframe().f_back.f_locals)
        return self.payload.format(**vars)

template = "The current name is {name}"

template_a = magic_fstring_function(template)

# use it inside a function to demonstrate it gets the scoping right
def new_scope():
    names = ["foo", "bar"]
    for name in names:
        print(template_a)

new_scope()
# The current name is foo
# The current name is bar

关于python - 如何推迟/推迟 f 弦的评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42497625/

相关文章:

python - 返回浮点(值)值错误: could not convert string to float in Django models

python - 构建Python : how to disable Py_LIMITED_API?

r - 将 rpy2 与 Pandas 数据框一起使用

c# - 转义字符关联性 C#6 字符串插值

android - Kotlin:如何获取字符串中 "@"之后的字符?

python - 在 reStructuredText(使用 Spinx)中使用文字 block 时如何修复列表缩进?

python - 尝试卡住 Python 3.6.5 应用程序时出现 _sysconfigdata 错误

python - 我正在尝试正确地可视化这个 lambda 问题,但我遇到了很多麻烦

python - 通过 Python 和 MySQL 使用参数化查询