Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conform long lines to fit PEP 8

Tags:

python

pep8

I have a question about styling in PEP 8 (or cutting the number of characters in each line to be smaller).

Consider that I have a book with a bunch of different attributes and I want to concatenate them into some String.

books = [book_1, book_2, book_3]
for b in books:
  print("Thank you for using our Library! You have decided to borrow %s on %s. Please remember to return the book in %d calendar days on %s" %    
  (book.title, book.start_date, book.lend_duration, book.return_date"))

How can I shorten this line to ensure its readability?

Any ideas will help. PEP 8 is just 1 idea.

like image 584
bryan.blackbee Avatar asked Jun 09 '16 04:06

bryan.blackbee


People also ask

What does PEP 8 recommend for the length of a line of code?

PEP 8 suggests lines should be limited to 79 characters. This is because it allows you to have multiple files open next to one another, while also avoiding line wrapping. Of course, keeping statements to 79 characters or less is not always possible. PEP 8 outlines ways to allow statements to run over several lines.

What is PEP 8 and why is it important?

PEP 8 is a document that provides various guidelines to write the readable in Python. PEP 8 describes how the developer can write beautiful code. It was officially written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The main aim of PEP is to enhance the readability and consistency of code.

How long should Python lines be?

The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72). The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.


2 Answers

You can move your string outside the loop, and then format it before printing, like this:

message = 'Thank you for using our Library! You have decided to borrow {0.title} \
           on {0.start_date}. Please remember to return the book in \
           {0.lend_duration} calendar days on {0.return_date}'

for i in books:
    print(message.format(i))
like image 172
Burhan Khalid Avatar answered Sep 30 '22 08:09

Burhan Khalid


As it's not mentioned in any other answer, you can use parenenthesis without using + or \:

>>> ("hello"
     " world")
'hello world'

Combined with Burhan's answer that gives you:

message = ('Thank you for using our Library! You have decided to borrow'
           ' {0.title} on {0.start_date}. Please remember to return the'
           ' book in {0.lend_duration} calendar days on {0.return_date}')

for b in books:
    print(message.format(b))
like image 40
Andy Hayden Avatar answered Sep 30 '22 08:09

Andy Hayden