python - 以字符串格式捕获 **vars() 模式

标签 python scope string-formatting

我经常发现自己使用以下模式来格式化字符串。

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 warnsinspect 模块可能不适合生产代码,因为它可能不适用于所有 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/

相关文章:

Python beautifulsoup 解析速度提升

python - 在 python 中处理不存在的属性最优雅的方法是什么?

ruby - 字符串中实际百分比的字符串插值

javascript - JavaScript Code School "Closures"任务中的打印问题

python - 如何使用字符串格式函数打印对象的表示形式?

python - 'for' 循环中的 i = i + 1 和 i += 1 有什么区别?

python - pandas.to_datetime() 如何从本地时区转换为 UTC unix 时间戳?

python - 类方法中未解析的引用

Python Jython 全局变量使用

r - 在 renderPlot 之外的 Shiny 中为 renderTable 提供一个对象