How to format Python code without really trying

Monday, March 30, 2015

Years of writing and maintaining Python code have taught us the value of automated tools for code formatting, but the existing ones didn’t quite do what we wanted. In the best traditions of the open source community, it was time to write yet another Python formatter.

YAPF takes a different approach to formatting Python code: it reformats the entire program, not just individual lines or constructs that violate a style guide rule. The ultimate goal is to let  engineers focus on the bigger picture and not worry about the formatting. The end result should look the same as if an engineer had worried about the formatting.

You can run YAPF on the entire program or just a part of the program. It’s also possible to flag certain parts of a program which YAPF shouldn’t alter, which is useful for generated files or sections with large literals.

Consider this horribly-formatted code:

x = {  'a':37,'b':42,


y = 'hello ''world'
z = 'hello '+'world'
a = 'hello {}'.format('world')
class foo  (     object  ):
 def f    (self   ):
   return       \
 def g(self, x,y=42):
     return y
def f  (   a ) :
 return      37+-+a[42-x :  y**3]

YAPF reformats this into something much more consistent and readable:

x = {'a': 37, 'b': 42, 'c': 927}

y = 'hello ' 'world'
z = 'hello ' + 'world'
a = 'hello {}'.format('world')

class foo(object):
   def f(self):
       return 37 * -+2

   def g(self, x, y=42):
       return y

def f(a):
   return 37 + -+a[42 - x:y ** 3]

Head to YAPF's GitHub page for more information on how to use it, and take a look at YAPF’s own source code to see a much larger example of the output it produces.

by Bill Wendling, YouTube Code Health Team