"executes" 一个 f 字符串的内部函数的名称是什么?
What is the name of the internal function that "executes" an f-string?
我读过 and 并看到许多(有效的)解决方案 exec
来推迟 f 字符串的执行,例如:
template = "My name is {name} and I am {age} years old"
name = 'Abcde'
age = 123
s = eval('f"""' + template + '"""') # My name is Abcde and I am 123 years old
是否有一个内部 Python 函数(在许多双下划线 __something__
函数中),它定义了解释器如何“运行”/“插入”一个 f 字符串?
Python源代码中有没有类似__runfstring__
的东西,负责代码的执行?如果是这样,我们可以自己调用这个函数吗:
s = __runfstring__(template)
在最新的 Python 版本中? (3.7 或 3.8+)
Is there an internal Python function (among the many double underscode __something__ functions), that defines how the interepreter "runs" / "interpolates" a f-string
答案是否。来自介绍 f 弦的 PEP 498:
The exact code used to implement f-strings is not specified. However, it is guaranteed that any embedded value that is converted to a string will use that value's __format__
method. This is the same mechanism that str.format()
uses to convert values to strings.
以及关于 Lexical Analysis in Formatted string literals 部分的文档:
If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion '!s' calls str()
on the result, '!r' calls repr()
, and '!a' calls ascii()
.
The result is then formatted using the format()
protocol. The format specifier is passed to the __format__()
method of the expression or conversion result. An empty string is passed when the format specifier is omitted. The formatted result is then included in the final value of the whole string.
所以没有为他们实施任何新。它们建立在现有协议之上。
我读过 exec
来推迟 f 字符串的执行,例如:
template = "My name is {name} and I am {age} years old"
name = 'Abcde'
age = 123
s = eval('f"""' + template + '"""') # My name is Abcde and I am 123 years old
是否有一个内部 Python 函数(在许多双下划线 __something__
函数中),它定义了解释器如何“运行”/“插入”一个 f 字符串?
Python源代码中有没有类似__runfstring__
的东西,负责代码的执行?如果是这样,我们可以自己调用这个函数吗:
s = __runfstring__(template)
在最新的 Python 版本中? (3.7 或 3.8+)
Is there an internal Python function (among the many double underscode __something__ functions), that defines how the interepreter "runs" / "interpolates" a f-string
答案是否。来自介绍 f 弦的 PEP 498:
The exact code used to implement f-strings is not specified. However, it is guaranteed that any embedded value that is converted to a string will use that value's
__format__
method. This is the same mechanism thatstr.format()
uses to convert values to strings.
以及关于 Lexical Analysis in Formatted string literals 部分的文档:
If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion '!s' calls
str()
on the result, '!r' callsrepr()
, and '!a' callsascii()
.The result is then formatted using the
format()
protocol. The format specifier is passed to the__format__()
method of the expression or conversion result. An empty string is passed when the format specifier is omitted. The formatted result is then included in the final value of the whole string.
所以没有为他们实施任何新。它们建立在现有协议之上。