我正在使用模板字符串生成一些文件,我喜欢新的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字符串,但我不知道是否存在这种情况.

Is there any way to bring in a string and have it interpreted as an f-string to avoid using the 100 call?

理想情况下,我希望能够像这样编码...(其中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-3.x相关问答推荐

类型的可变性对变量的作用域有影响吗?

如何验证具有内部json字符串的json字符串?

如何将参数/值从测试方法传递给pytest的fixture函数?

如何将项目添加到Python中具有固定大小的列表列表中

AddMultplicationEquality() 用于多个变量

Select 作为 MultiIndex 一部分的两个 DatetimeIndex 之间的行

在Python中基于组/ID将两个数据帧进行映射,找出较接近的值

如何沿单列获取嵌套列表中的唯一值?

安装没有 sudo 权限的 python3 和 pip3

使用 OpenCV 从图像中减go 一条线

Einsum 对于张量乘法很慢

Python BeautifulSoup:在 Select 语句中排除其他标签

Dask worker post-processing

为直方图中的每个 bin 绘制不同的 colored颜色 (Matplotlib)

如何使用pandas python获取数据框中每列的最大长度

在 Pandas 数据框中显示对图

为什么 2to3 将 mydict.keys() 更改为 list(mydict.keys())?

从大字典中弹出 N 项的最快方法

用于 unicode 大写单词的 Python 正则表达式

Python - 类 __hash__ 方法和集合