以字符串格式捕获 **vars() 模式 [英] Capturing **vars() pattern in string formatting

查看:33
本文介绍了以字符串格式捕获 **vars() 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己使用以下模式进行字符串格式化.

I frequently find myself using the following pattern for 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()) 模式似乎非常不合逻辑.

That is, I often have the values I need to print in the local namespace, represented by a call to vars(). As I look over my code, however, it seems awfully unpythonic to be constantly repeating the .format(**vars()) pattern.

我想创建一个函数来捕捉这种模式.将类似于以下内容.

I'd like to create a function that will capture this pattern. It would be something like the following.

# 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() 不再是我想要的.

Except that by the time I'm in the lfmt namespace, vars() is no longer what I want.

如何编写 lfmt 以便它在调用者的命名空间中执行 vars() 以便以下代码可以像上面的示例一样工作?

How can I write lfmt so that it executes vars() in the caller's namespace such that the following code would work as the example above?

print(lfmt('a is {a}, b is {b}, mykey is {c[mykey]}'))

推荐答案

Edit:为了使 lfmt 在从不同的命名空间调用时能够正常工作,您需要检查模块.请注意,正如文档警告inspect 模块可能不适合生产代码,因为它可能不适用于 Python 的所有实现

Edit: In order for lfmt to work when called from different namespaces, you'll need the inspect module. Note, as the documentation warns, the inspect module may not be suitable for production code since it may not work with all implementations of 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

这篇关于以字符串格式捕获 **vars() 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆