16

I have this line of code:

assert 0 <= j <= self.n, "First edge needs to be between 0 and {}".format(self.n)

I want pep8 to be happy, but I don't understand how to break this line. I tried breaking after the comma and got invalid syntax. I've tried breaking the string with additional ""'s as in How to break long string lines for PEP8 compliance?. PEP8 was happy but the assert only produced the first half of the message.

What is the proper way to break long assert strings?

Community
  • 1
  • 1
Aguy
  • 7,851
  • 5
  • 31
  • 58
  • 12
    Break PEP8 instead. – MatsLindh Jul 02 '16 at 22:45
  • 1
    You could add a backslash after the comma and put the rest on a new line. – fenceop Jul 02 '16 at 22:46
  • 3
    Personally, I'd go for a *slightly* more readable version: Assign the failure message to a variable, and use that variable in assert. – UltraInstinct Jul 02 '16 at 22:47
  • See also [How can I break up this long line in Python?](http://stackoverflow.com/questions/2058925/how-can-i-break-up-this-long-line-in-python) – Peter Wood Jul 03 '16 at 08:20
  • You might not need to break your lines anymore, and even if, fstring works better for these kinds of use cases: ```assert 0 <= j <= self.n, f"First edge needs to be between 0 and {self.n}"``` It is more concise. – Oladimeji Mudele Aug 01 '19 at 13:32

3 Answers3

18

Use parens:

assert 0 <= j <= self.n, ("First edge needs to be "
                          "between 0 and {}".format(self.n))

Or:

assert 0 <= j <= self.n, ("First edge needs to be between 0 and {}"
                          .format(self.n))

Or use the parens of the format function:

assert 0 <= j <= self.n, "First edge needs to be between 0 and {}".format(
    self.n)
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
8

Considering assert statements can be optimized away when you run the interpreter with the -O option, you probably want to keep it a single statement and use string concatenation in parenthesis:

assert 0 <= j <= self.n, ('First edge needs to be between '
                          '0 and {}'.format(self.n))

or using f-strings in Python 3.6+:

assert 0 <= j <= self.n, ('First edge needs to be between '
                          f'0 and {self.n}')

If you don't care about optimization (e.g. you're writing tests), then breaking the line into two statements is also an option:

message = 'First edge needs to be between 0 and {}'.format(self.n)
assert 0 <= j <= self.n, message
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
3

You can force breaking to a new line like this:

assert 0 <= j <= self.n,\
       "print stuff"

That always makes the line continue, if brackets and such aren't doing it automatically. And you can indent the next line to wherever makes it the most readable, as I did above.

Jeff
  • 2,158
  • 1
  • 16
  • 29