Search code examples
pythonindentationbracketspep8

PEP8 formatting: long line with indentation and nested brackets


As a python beginner, I've been looking for a PEP8-compliant way of formatting the following line of code (that also makes PyCharm happy). Here it is:

print("{}! The {} {} ".format(self.monster.battlecry(),
                              self.monster.color,
                              self.monster.__class__.__name__)
      + self.monster_deaths.pop(self.monster_deaths.index(random.choice(self.monster_deaths))))

I'm especially worried about the last line with the 4 brackets at the end. Also, should I indent the last line by 4 spaces as usual, or a bit more to align it to the content of print ?

Would the following be more appropriate?

print("{}! The {} {} ".format(self.monster.battlecry(),
                              self.monster.color,
                              self.monster.__class__.__name__)
       + self.monster_deaths.pop(
             self.monster_deaths.index(
                 random.choice(self.monster_deaths)
                 )
             )
      )

An alternative would be to shorten this ugly line by creating a variable d = self.monster_deaths. What do you think?


Solution

  • the alternative to shorten the line with a temporary variable is the right way. In that case, you can also add it to the format statement rather than using string concatenation:

    d = self.monster_deaths.pop(...)
    print("{}! The {} {} {}".format(self.monster.battlecry(),
                                    self.monster.color,
                                    type(self.monster).name,
                                    d))