7

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?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Wyrmwood
  • 3,340
  • 29
  • 33

1 Answers1

9

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.

Community
  • 1
  • 1
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • @Wyrmwood, It works but it does look right to me. F-strings are meant to improve readability, so including one 79characters long expression inside braces is kind of unpythonic. And at the end you're just reformatting a oneliner on multiple lines... – FabienP Sep 29 '17 at 20:13
  • @Wyrmwood, [look here](http://docs.python-guide.org/en/latest/writing/style/) for more info on "pythonic", and at [PEP20](https://www.python.org/dev/peps/pep-0020/) for Python coding principles. – FabienP Sep 30 '17 at 16:51