Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For example, if I have

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

Because there's very little actual text, there's no good place prior to 79 characters to break the line. It appears you cannot do this:

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

The only thing I've been able to do is split up the command, like:

>>> 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'

Is there any other option to split the f-string?

like image 408
Wyrmwood Avatar asked Jan 29 '23 12:01

Wyrmwood


1 Answers

Yes, you can still use triple-quotes strings and split it in any way you think is best.

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.

So any whitespace before and after is removed, additional whitespace inside parentheses (e.g the function calls) and square/curly brackets also makes no difference for the same reason. So this:

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

should still yield the expected result. Format it in the way you deem best.

Though one could succesfully argue that you can trim everything down with a few other steps:

# 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"

the choice is ultimately yours.

like image 61
Dimitris Fasarakis Hilliard Avatar answered Feb 14 '23 17:02

Dimitris Fasarakis Hilliard