Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code formatting

Tags:

python

In response to another question of mine, someone suggested that I avoid long lines in the code and to use PEP-8 rules when writing Python code. One of the PEP-8 rules suggested avoiding lines which are longer than 80 characters. I changed a lot of my code to comply with this requirement without any problems. However, changing the following line in the manner shown below breaks the code. Any ideas why? Does it have to do with the fact that what follows return command has to be in a single line?

The line longer that 80 characters:

    def __str__(self):
    return "Car Type \n"+"mpg: %.1f \n" % self.mpg + "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)

The line changed by using Enter key and Spaces as necessary:

    def __str__(self):
    return "Car Type \n"+"mpg: %.1f \n" % self.mpg + 
                   "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +
                   "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
like image 572
Curious2learn Avatar asked Nov 27 '22 23:11

Curious2learn


2 Answers

A multiline string would be more readable:

def __str__(self):
    return '''\
Car Type
mpg: %.1f
hp: %.2f 
pc: %i 
unit cost: $%.2f
price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price)

To maintain visually meaningful indentation levels, use textwrap.dedent:

import textwrap
def __str__(self):
    return textwrap.dedent('''\
        Car Type
        mpg: %.1f
        hp: %.2f
        pc: %i
        unit cost: $%.2f
        price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price))
like image 160
unutbu Avatar answered Nov 30 '22 12:11

unutbu


You can solve the problem by putting the expression in parenthesis:

def __str__(self):
    return ("Car Type \n"+"mpg: %.1f \n" % self.mpg + 
            "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +
            "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price))

However, I'd consider writing it more like this: (code untested)

def __str__(self):
    return """\
Car Type 
mpg: %(mpg).1f 
hp: %(hp).2f
pc: %(pc)i 
unit cost: $%(cost).2f 
price: $%(price).2f """ % self.__dict__
like image 35
Daniel Stutzbach Avatar answered Nov 30 '22 13:11

Daniel Stutzbach