PEP8 breaking long string in assert

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.


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

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)

Tags:

Python