跳转到主要内容

执行延迟f-string评估的库。

项目描述

fstr

Build Status PyPI Code style: black License: MIT

1. 在Python 2中使用f-string语法

import fstr

x = 1
y = 2

template = fstr("{x} + {y} = {x + y}")

print(template.evaluate())
1 + 2 = 3

2. 在Python 2和3中使用f-string语法代替str.format

import fstr

common_error_message = fstr("function {function.__name__!r} failed because {error}")

def add(x, y):
    try:
        return x + y
    except Exception as e:
        msg = common_error_message.format(function=add, error=e)
        print(msg)

def sub(x, y):
    try:
        return x + y
    except Exception as e:
        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中定义的一些功能。`fstr`的测试用例甚至是从CPython的测试套件中提取的(进行了少量修改)。

格式说明符

格式说明符可以包含评估后的表达式。

import fstr
import decimal

width = 10
precision = 4
value = decimal.Decimal('12.34567')

fstr("result: {value:{width}.{precision}}").evaluate()
'result:      12.35'

一旦格式说明符中的表达式被评估(如果需要),格式说明符就不会被f-string评估器解释。就像在`str.format()`中一样,它们只是传递给正在格式化的对象的`__format__()`方法。

表达式中的Lambda函数

import fstr

fstr("{(lambda x: x*2)(3)}").format()
'6'

错误处理

确切的消息将根据你是否使用Python<3.6而有所不同。


import fstr

fstr("x={x")
File "fstr", line 1
  x={x
      ^
SyntaxError: Mismatched braces in f-string.

import fstr

fstr("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模板。

例如,这将会比如果你在循环外定义模板时

for i in range(10):
   s = fstr("{i}**2 = {i**2}").format(i=i)

慢得多

template = fstr("{i}**2 = {i**2}")

for i in range(10):
   s = template.format(i=i)

str.formatfstr.format

from timeit import timeit

str_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

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

fstr-0.1.0a2.tar.gz (6.8 kB 查看哈希值)

上传时间

构建分布

fstr-0.1.0a2-py3-none-any.whl (6.9 kB 查看哈希值)

上传时间 Python 3

由以下支持