有没有办法在大括号内分解 f 弦?

Is there any way to break up an f-string within the braces?

例如,如果我有

>>> name = f"{os.path.splitext(os.path.basename('/some/long/path/I/donot/need/to/some/config.bs'))[0]}.yaml"
'config.yaml'

因为实际文本很少,所以在 79 个字符之前没有好的地方可以换行。看来你不能这样做:

name = f"{os.path.splitext(os.path.basename(
    '/some/long/path/I/donot/need/to/some/config.bs'))[0]}.yaml"

>>> f"{os.path.splitext(os.path.basename(
  File "<stdin>", line 1
    f"{os.path.splitext(os.path.basename(
                                        ^
SyntaxError: EOL while scanning string literal

我唯一能做的就是拆分命令,例如:

>>> fname = '/some/long/path/I/donot/need/to/some/config.bs'
>>> tempname = os.path.splitext(os.path.basename(
...     fname))[0]
>>> name = f'{tempname}.yaml'
>>> name
'config.yaml'

是否还有其他拆分 f 弦的选项?

是的,您仍然可以使用三引号字符串并以您认为最好的任何方式拆分它。

From the PEP on f-strings:

Leading and trailing whitespace in expressions is ignored

For ease of readability, leading and trailing whitespace in expressions is ignored. This is a by-product of enclosing the expression in parentheses before evaluation.

所以删除前后的任何空格,括号内的额外空格(例如函数调用)和 square/curly 括号也没有区别,原因相同。所以这个:

name = f"""{
    os.path.splitext(
        os.path.basename('/some/long/path/I/donot/need/to/some/config.bs')
    )[0]}.yaml"""

应该仍会产生预期的结果。按照您认为最好的方式进行格式化。

尽管有人可以成功地争辩说您可以 trim 通过其他几个步骤解决所有问题:

# not using fully qualified name
from os.path import splitext, basename

fname = '/some/long/path/I/donot/need/to/some/config.bs'
name = f"{splitext(basename(fname))[0].yaml"

最终选择权在您。