A formatter for Python files
YAPF is a Python formatter based on clang-format
(developed by Daniel Jasper). In essence, the algorithm takes the code and
calculates the best formatting that conforms to the configured style. It takes
away a lot of the drudgery of maintaining your code.
The ultimate goal is that the code YAPF produces is as good as the code that a programmer would write if they were following the style guide.
Note YAPF is not an official Google product (experimental or otherwise), it is just code that happens to be owned by Google.
To install YAPF from PyPI:
$ pip install yapfYAPF is still considered in "beta" stage, and the released version may change often; therefore, the best way to keep up-to-date with the latest development is to clone this repository or install directly from github:
$ pip install git+https://github.com/google/yapf.gitNote that if you intend to use YAPF as a command-line tool rather than as a
library, installation is not necessary. YAPF supports being run as a directory
by the Python interpreter. If you cloned/unzipped YAPF into DIR, it's
possible to run:
$ PYTHONPATH=DIR python DIR/yapf [options] ...YAPF is supported by multiple editors via community extensions or plugins. See Editor Support for more info.
YAPF supports Python 3.7+.
…Normally YAPF returns zero on successful program termination and non-zero otherwise.
If --diff is supplied, YAPF returns zero when no changes were necessary,
non-zero otherwise (including program error). You can use this in a CI workflow
to test that code has been YAPF-formatted.
In addition to exclude patterns provided on commandline, YAPF looks for
additional patterns specified in a file named .yapfignore or pyproject.toml
located in the working directory from which YAPF is invoked.
.yapfignore's syntax is similar to UNIX's filename pattern matching:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seqNote that no entry should begin with ./.
If you use pyproject.toml, exclude patterns are specified by ignore_patterns key
in [tool.yapfignore] section. For example:
[tool.yapfignore]
ignore_patterns = [
"temp/**/*.py",
"temp2/*.py"
]The formatting style used by YAPF is configurable and there are many "knobs"
that can be used to tune how YAPF does formatting. See the style.py module
for the full list.
To control the style, run YAPF with the --style argument. It accepts one of
the predefined styles (e.g., pep8 or google), a path to a configuration
file that specifies the desired style, or a dictionary of key/value pairs.
The config file is a simple listing of (case-insensitive) key = value pairs
with a [style] heading. For example:
[style]
based_on_style = pep8
spaces_before_comment = 4
split_before_logical_operator = trueThe based_on_style setting determines which of the predefined styles this
custom style is based on (think of it like subclassing). Four
styles are predefined:
pep8 (default)google (based off of the Google Python Style Guide)yapf (for use with Google open source projects)facebookSee _STYLE_NAME_TO_FACTORY in style.py for details.
It's also possible to do the same on the command line with a dictionary. For example:
--style='{based_on_style: pep8, indent_width: 2}'This will take the pep8 base style and modify it to have two space
indentations.
YAPF will search for the formatting style in the following manner:
[style] section of a .style.yapf file in either the current
directory or one of its parent directories.[yapf] section of a setup.cfg file in either the current
directory or one of its parent directories.[tool.yapf] section of a pyproject.toml file in either the current
directory or one of its parent directories.[style] section of a ~/.config/yapf/style file in your home
directory.If none of those files are found, the default style PEP8 is used.
An example of the type of formatting that YAPF can do, it will take this ugly code:
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]and reformat it into:
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]The two main APIs for calling YAPF are FormatCode and FormatFile, these
share several arguments which are described below:
>>> from yapf.yapflib.yapf_api import FormatCode # reformat a string of code
>>> formatted_code, changed = FormatCode("f ( a = 1, b = 2 )")
>>> formatted_code
'f(a=1, b=2)\n'
>>> changed
TrueA style_config argument: Either a style name or a path to a file that
contains formatting style settings. If None is specified, use the default style
as set in style.DEFAULT_STYLE_FACTORY.
>>> FormatCode("def g():\n return True", style_config='pep8')[0]
'def g():\n return True\n'A lines argument: A list of tuples of lines (ints), [start, end], that we
want to format. The lines are 1-based indexed. It can be used by third-party
code (e.g., IDEs) when reformatting a snippet of code rather than a whole file.
>>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])[0]
'def g():\n a = 1\n b = 2\n return a==b\n'A print_diff (bool): Instead of returning the reformatted source, return a
diff that turns the formatted source into reformatted source.
>>> print(FormatCode("a==b", filename="foo.py", print_diff=True)[0])
--- foo.py (original)
+++ foo.py (reformatted)
@@ -1 +1 @@
-a==b
+a == bNote: the filename argument for FormatCode is what is inserted into the
diff, the default is <unknown>.
FormatFile returns reformatted code from the passed file along with its encoding:
>>> from yapf.yapflib.yapf_api import FormatFile # reformat a file
>>> print(open("foo.py").read()) # contents of file
a==b
>>> reformatted_code, encoding, changed = FormatFile("foo.py")
>>> formatted_code
'a == b\n'
>>> encoding
'utf-8'
>>> changed
TrueThe in_place argument saves the reformatted code back to the file:
>>> FormatFile("foo.py", in_place=True)[:2]
(None, 'utf-8')
>>> print(open("foo.py").read()) # contents of file (now fixed)
a == bOptions:
…ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENTAlign closing bracket with visual indentation.
ALLOW_MULTILINE_LAMBDASAllow lambdas to be formatted on more than one line.
ALLOW_MULTILINE_DICTIONARY_KEYSAllow dictionary keys to exist on multiple lines. For example:
x = {
('this is the first element of a tuple',
'this is the second element of a tuple'):
value,
}ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNSAllow splitting before a default / named assignment in an argument list.
ALLOW_SPLIT_BEFORE_DICT_VALUEAllow splits before the dictionary value.
ARITHMETIC_PRECEDENCE_INDICATIONLet spacing indicate operator precedence. For example:
a = 1 * 2 + 3 / 4
b = 1 / 2 - 3 * 4
c = (1 + 2) * (3 - 4)
d = (1 - 2) / (3 + 4)
e = 1 * 2 - 3
f = 1 + 2 + 3 + 4will be formatted as follows to indicate precedence:
a = 1*2 + 3/4
b = 1/2 - 3*4
c = (1+2) * (3-4)
d = (1-2) / (3+4)
e = 1*2 - 3
f = 1 + 2 + 3 + 4BLANK_LINES_AROUND_TOP_LEVEL_DEFINITIONSets the number of desired blank lines surrounding top-level function and class definitions. For example:
class Foo:
pass
# <------ having two blank lines here
# <------ is the default setting
class Bar:
passBLANK_LINE_BEFORE_CLASS_DOCSTRINGInsert a blank line before a class-level docstring.
BLANK_LINE_BEFORE_MODULE_DOCSTRINGInsert a blank line before a module docstring.
BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEFInsert a blank line before a
deforclassimmediately nested within anotherdeforclass. For example:
class Foo:
# <------ this blank line
def method():
passBLANK_LINES_BETWEEN_TOP_LEVEL_IMPORTS_AND_VARIABLESSets the number of desired blank lines between top-level imports and variable definitions. Useful for compatibility with tools like isort.
COALESCE_BRACKETSDo not split consecutive brackets. Only relevant when
DEDENT_CLOSING_BRACKETSorINDENT_CLOSING_BRACKETSis set. For example:
call_func_that_takes_a_dict(
{
'key1': 'value1',
'key2': 'value2',
}
)would reformat to:
call_func_that_takes_a_dict({
'key1': 'value1',
'key2': 'value2',
})COLUMN_LIMITThe column limit (or max line-length)
CONTINUATION_ALIGN_STYLEThe style for continuation alignment. Possible values are:
SPACE: Use spaces for continuation alignment. This is default behavior.FIXED: Use fixed number (CONTINUATION_INDENT_WIDTH) of columns (i.e.CONTINUATION_INDENT_WIDTH/INDENT_WIDTHtabs orCONTINUATION_INDENT_WIDTHspaces) for continuation alignment.VALIGN-RIGHT: Vertically align continuation lines to multiple ofINDENT_WIDTHcolumns. Slightly right (one tab or a few spaces) if cannot vertically align continuation lines with indent characters.
CONTINUATION_INDENT_WIDTHIndent width used for line continuations.
DEDENT_CLOSING_BRACKETSPut closing brackets on a separate line, dedented, if the bracketed expression can't fit in a single line. Applies to all kinds of brackets, including function definitions and calls. For example:
config = {
'key1': 'value1',
'key2': 'value2',
} # <--- this bracket is dedented and on a separate line
time_series = self.remote_client.query_entity_counters(
entity='dev3246.region1',
key='dns.query_latency_tcp',
transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
start_ts=now()-timedelta(days=3Support Python 3.14 unparenthesized exception lists (PEP 758)
Feature Request: `split_after_opening_bracket=False`
YAPF 2: Replatform off of lib2to3 to libcst and structured pattern matching (2025 project idea)
Yapf breaks with type variables
Support 3.12 feature: PEP 695 Type Parameter Syntax
omitting [style] breaks yapf
Windows: grammar-cache creation can hang when cache writes are denied
[Bug]: ParseError when using dictionary in logging.getLogger
Is this this project maintained??
[Bug][Crash][Reproducible] IndexError: tuple index out of range