我经常发现自己使用以下模式来格式化字符串。
a = 3
b = 'foo'
c = dict(mykey='myval')
#prints a is 3, b is foo, mykey is myval
print('a is {a}, b is {b}, mykey is {c[mykey]}'.format(**vars()))
也就是说,我经常在本地命名空间中拥有需要打印的值,通过调用 vars() 来表示。然而,当我查看我的代码时,不断重复 .format(**vars())
模式似乎非常不符合 pythonic。
我想创建一个函数来捕捉这种模式。它将类似于以下内容。
# doesn't work
def lfmt(s):
"""
lfmt (local format) will format the string using variables
in the caller's local namespace.
"""
return s.format(**vars())
除了当我进入 lfmt
命名空间时,vars() 不再是我想要的。
我如何编写 lfmt 以便它在调用者的命名空间中执行 vars() 以便下面的代码可以像上面的示例一样工作?
print(lfmt('a is {a}, b is {b}, mykey is {c[mykey]}'))
最佳答案
编辑:为了使 lfmt
在从不同命名空间调用时能够正常工作,您将需要 inspect
模块。注意,作为 the documentation warns ,inspect
模块可能不适合生产代码,因为它可能不适用于所有 Python 实现
import inspect
def lfmt(s):
caller = inspect.currentframe().f_back
return s.format(**caller.f_locals)
a = 3
b = 'foo'
c = dict(mykey='myval')
print(lfmt('a is {a}, b is {b}, mykey is {c[mykey]}'))
# a is 3, b is foo, mykey is myval
关于python - 以字符串格式捕获 **vars() 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2201867/