python - 从其调用范围中提取变量的字符串格式化程序是不好的做法吗?

标签 python

我有一些代码可以进行大量的字符串格式化,通常,我最终得到的代码如下:

"...".format(x=x, y=y, z=z, foo=foo, ...)

我试图将大量变量插入到一个大字符串中。

是否有充分的理由不编写这样一个使用 inspect 模块来查找要插入的变量的函数?

import inspect

def interpolate(s):
    return s.format(**inspect.currentframe().f_back.f_locals)

def generateTheString(x):
    y = foo(x)
    z = x + y
    # more calculations go here
    return interpolate("{x}, {y}, {z}")

最佳答案

更新:Python 3.6 内置了这个功能(一个更强大的变体):

x, y, z = range(3)
print(f"{x} {y + z}")
# -> 0 3

参见 PEP 0498 -- Literal String Interpolation


[手动解决方案] 会导致嵌套函数出现一些令人惊讶的行为:

from callerscope import format

def outer():
    def inner():
        nonlocal a
        try:
            print(format("{a} {b}"))
        except KeyError as e:
            assert e.args[0] == 'b'
        else:
            assert 0

    def inner_read_b():
        nonlocal a
        print(b) # read `b` from outer()
        try:
            print(format("{a} {b}"))
        except KeyError as e:
            assert 0
    a, b = "ab"
    inner()
    inner_read_b()

注意:同一调用成功或失败取决于变量是在其上方还是下方某处被提及。

callerscope 在哪里:

import inspect
from collections import ChainMap
from string import Formatter

def format(format_string, *args, _format=Formatter().vformat, **kwargs):
    caller_locals = inspect.currentframe().f_back.f_locals
    return _format(format_string, args, ChainMap(kwargs, caller_locals))

关于python - 从其调用范围中提取变量的字符串格式化程序是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13312240/

相关文章:

python - tox/pytest 测试通过/失败取决于主机环境中是否安装了另一个模块

python - 在 Keras 中声明转换后的序列的 input_shape?

Python 3.5 MySQL 连接器

python - 在 sklearn 的 .fit() 方法中使用 numpy.ndarray 与 Pandas Dataframe

python - matplotlib 相邻子图 : adding colorbar changes size of a subplot

python - 为什么这个生成器表达式函数比循环版本慢?

python - 接收一个列表,根据连续的重复值返回 True/False 列表

python - 将数据从 Django View 传递到 D3

python - 在 numba 中创建一个空列表列表

python - 当 Python Watchdog 的目录发生任何变化时如何运行函数?