PEP8 breaks a long line in a statement

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 to crack a comma and got invalid syntax. I tried to break the line with the optional β€œlike in How to split long lines of lines to match PEP8?. PEP8 was happy, but the statement only produced the first half of the message.

What is the correct way to break long assert lines?

+6
source share
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 parsers of the format function:

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

Given that assert can be optimized when you run the interpreter with -O , you probably want to store it in a single statement and use string concatenation in brackets:

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

or using f-lines in Python 3.6+:

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

If you are not interested in optimization (for example, you write tests), then the option of splitting into two operators is also possible:

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

You can force it to break into a new line as follows:

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

This always makes the line extended if parentheses, etc. Do not do this automatically. And you can step back to the next line to where it makes it most readable, as I said above.

+2
source

All Articles