gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:18:47 24 4
gpt4 key购买 nike

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

"...".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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com