用于执行延迟的F字符串计算的库。
fstr的Python项目详细描述
fstr
1在python 2中使用f-string语法:
importfstrx=1y=2template=fstr("{x} + {y} = {x + y}")print(template.evaluate())
1 + 2 = 3
2。在python 2和3中使用f-string语法而不是str.format
:
importfstrcommon_error_message=fstr("function {function.__name__!r} failed because {error}")defadd(x,y):try:returnx+yexceptExceptionase:msg=common_error_message.format(function=add,error=e)print(msg)defsub(x,y):try:returnx+yexceptExceptionase:msg=common_error_message.format(function=sub,error=e)print(msg)add(1,"2")sub("5",3)
function 'add' failed because unsupported operand type(s) for +: 'int' and 'str'
function 'sub' failed because can only concatenate str (not "int") to str
完全PEP-498符合性
python 2中f-string语法的其他向后兼容库只实现了pep的specification中定义的一些功能。对fstr
的测试用例甚至从CPython's test suite中提升(有一些细微的变化)。
格式说明符
格式说明符可以包含计算表达式。
importfstrimportdecimalwidth=10precision=4value=decimal.Decimal('12.34567')fstr("result: {value:{width}.{precision}}").evaluate()
'result: 12.35'
一旦对格式说明符中的表达式求值(如有必要),格式说明符就不会被f-string求值器解释就像在str.format()
中一样,它们仅仅被传递到正在格式化的对象的__format__()
方法中
表达式中的lambdas
importfstrfstr("{(lambda x: x*2)(3)}").format()
'6'
错误处理
确切的消息将根据您是否使用Python<;3.6而有所不同
importfstrfstr("x={x")
File "fstr", line 1
x={x
^
SyntaxError: Mismatched braces in f-string.
importfstrfstr("x={!x}")
File "fstr", line 1
x={!x}
^
SyntaxError: Empty expresion not allowed.
性能考虑
fstr
并不意味着要替代python的f-string语法。相反,它主要用作在
否则可能使用str.format
的情况。另外,Python的f-string语法能够在编译时进行性能优化,而这些优化不是提供给str.format
或fstr.format
鉴于此,我们只比较fstr.format
和str.format
。
fstr
的性能取决于您是否:
- 是否使用python<;3.6。
- 提前定义f-string模板。
例如,这将显著减慢。
如果在循环外定义模板:foriinrange(10):s=fstr("{i}**2 = {i**2}").format(i=i)
template=fstr("{i}**2 = {i**2}")foriinrange(10):s=template.format(i=i)
str.format
对fstr.format
fromtimeitimporttimeitstr_setup="template = '{x}' * 10"fstr_setup="import fstr\ntemplate = fstr('{x}' * 10)"str_result=timeit("template.format(x=1)",setup=str_setup,number=1000000)fstr_result=timeit("template.format(x=1)",setup=fstr_setup,number=1000000)print("str.format() : %s seconds"%str_result)print("fstr.format() : %s seconds"%fstr_result)
Python<;3.6
str.format() : 0.741672992706 seconds
fstr.format() : 6.77992010117 seconds
Python=3.6
str.format: 0.7007193689933047 seconds
fstr.format: 0.9083925349987112 seconds
推荐PyPI第三方库