Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PEP8 breaking long string in assert [duplicate]

Tags:

python

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?

like image 209
Aguy Avatar asked Jul 02 '16 22:07

Aguy


3 Answers

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)
like image 144
Peter Wood Avatar answered Nov 18 '22 15:11

Peter Wood


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
like image 42
Eugene Yarmash Avatar answered Nov 18 '22 14:11

Eugene Yarmash


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.

like image 3
Jeff Avatar answered Nov 18 '22 14:11

Jeff