
Format Python Code Using YAPF - keyboardman
https://leimao.github.io/blog/YAPF-Quick-Tutorial/
======
fermigier
I've used Yapf for a year, then switched to Black when it appeared.

Seriously, use Black. I my experience, and to my taste, it works perfectly all
the time, and the result is beautiful.

It's also pep8 compliant, for the parts of pep8 that are concerned by a
reformatter.

~~~
lapink
Black produces code with more lines than yapf. Sure sometimes yapf makes very
weird decision (especially when using a dictionary litteral as an argument to
a function) but at least it does not use 4 lines for a list with 2 items that
could have fitted on one line.

~~~
weberc2
I’m pretty sure Black doesn’t do that, it will fit them onto a single line if
possible, then it will move the kv pairs onto their own line, and failing
that, one kv pair per line. In any case, I’m fine with more lines. Clarity is
much more important than minimizing line count.

~~~
lunixbochs
I've seen Black do this (the dict needs to be too long to inline):

    
    
      call(
          {
              "key": "value",
              "key": "value",
          }
      )

~~~
guitarbill
yeah, can be annoying, but also encourages this, which is nice when the number
of values grows:

    
    
      items = {
          "key": "value",
          "key": "value",
      }
      call(items)
    

it's a bit annoying with exception messages, but again, writing long args
before works great, and i've become a fan of this (unintended?) nudge:

    
    
      if error:
          raise ValueError(
              "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas vel ligula nec eros finibus metus."
          )
    
      if error:
          msg = (
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
            "Maecenas vel ligula nec eros finibus metus."
          )
          raise ValueError(msg)
    

just to be clear, i don't think working around a formatter is good. in this
case, i feel like the uncompromising rules were exposing a bit of an anti-
pattern. obviously, your opinion on this may vary wildly.

~~~
edflsafoiewq
This puts the lie to the common claim that formatters end formatting
decisions. Actually they only move the problem from "how shall I format my
code" to "how shall I write my code so that I will like the way my
autoformatter formats my code".

~~~
weberc2
You misunderstand the point of formatters. They aren’t meant to automate your
personal preference; they automate a standard format so your team doesn’t have
to waste time deciding on and enforcing a coding standard and so you don’t
have to manually implement the standard. Implicit in using a code formatter is
the decision to stop navel gazing and put the team first.

------
BiteCode_dev
I dislike a lot of black decisions and still use it for everything.

My aesthetic taste is less important than getting things done.

If you are not using it, stop arguing and nit picking about your preferences,
we, as a community, have more important things to do. It will hurt only a
little, I promise.

~~~
ScoutOrgo
My team has a handful of junior data scientists that really don't have a lot
of experience of coding "well". Black was super helpful in 1, getting people
used to decent coding format and 2, removing any effort or discussion around
formatting in PRs. I added the formatting to pre-commit and the rest is
effortless.

------
hashhar
The only successful formatter are ones who don't have any knobs to tune. The
reason a formatter exists is to make all codebases look consistent, not to
cater to your personal style.

This is one area Golang got it right with gofmt.

~~~
Lutzb
This is the reason we switched to black for Python about a year ago. There are
no options to tweak. At first I had to deal with a lot of complaining
developers, but now everyone got accustomed to blacks formatting style and we
moved on.

~~~
londt8
It has questionable default of 88 characters per line, which is configurable.
I wish they chose 79 characters as PEP8 suggests.

~~~
zzzeek
That is one of the few things you can set, put it in your pyproject.toml,
done.

Oh you don't have a pyproject.toml? Well then we have a different problem :)

------
no_wizard
We used YAPF[0] before we used Black[1]

I really liked it, a lot. What set Black above is it is most of the decisions
(if not all, really) makes is how we setup YAPF anyway. I do think it does
some small things better, like reformatting function arguments in certain
cases (as is highlighted elsewhere in this thread)

If you need configurability, YAPF is the best choice, in my opinion. We still
use isort though, because it sorts imports in a much more readable way.

I just wish I could find a suitable replacement for C# development. StyleCop
is okay, but I find we have to use `<NoWarn></NoWarn>` .csproj settings on so
many little rules and it doesn't auto format (in as so far as I can tell). If
your editor supports it, it will use it as a formatting source of truth,
though. I just want something that also has a runnable console binary we can
use in CI. Maybe I haven't looked at it closely enough.

[0][https://github.com/google/yapf](https://github.com/google/yapf)

[1][https://black.readthedocs.io/en/stable/](https://black.readthedocs.io/en/stable/)

------
miguendes
I use black and couldn't be happier. Very fast and produces very readable
code.

------
tzs
Some editors or IDEs have pretty good automatic "formatting as you type"
systems that can largely remove the need for stand-alone formatters for new
code.

Sometimes you can convince them to processes an existing file as if it is
being typed in and so apply the "as you type" formatter, effectively giving
you a stand-alone formatter.

I used to do this with Emacs for C formatting. I don't remember how since I'm
a vim user who only figured out enough Emacs for this one thing, and it was a
long time ago, but I remember it worked very well. The Emacs C "as you type"
formatter was very configurable and I was able to make it almost perfectly
match my employer's style.

How's Emacs "as you type" Python formatting?

------
zelly
I thought the community standardized on black

~~~
scrollaway
Black is just slightly too opinionated. It gives you configuration options for
benign things such as numeric separators, but it flat out refuses to allow tab
indent, which a fairly significant part of the python community uses.

I tried to PR a --use-tabs flag but the PR was rejected without comments. Had
to fork Black to be able to use it. Tan is a drop-in replacement that allows
--use-tabs (and use-tabs = true in pyproject.toml).

[https://github.com/jleclanche/tan](https://github.com/jleclanche/tan)

~~~
stubish
The reason Black is fast becoming standard is precisely _because_ it is so
opinionated. Like the other code formatters that have successfully become
'normal', such as gofmt. An option means that there isn't a standard, but
several standards. And the people pushing Black in their projects see the
benefit of a global standard, even though it is rarely 100% _their_ personal
preferences. It is a consensus.

~~~
scrollaway
Prettier is more widespread than black, is very opinionated, and still has an
option for tab indent. This is a strawman.

~~~
stubish
Prettier's opinion then is that tabs are irrelevant to the formatting. Which
is probably fine for the all the languages Prettier seems to support. Unlike
Python, where tabs vs spaces matter. Mixing tabs and spaces is a problem, and
a formatter cannot automatically support both or risks changing the meaning of
code.

~~~
scrollaway
I don't know how you arrive to this conclusion… prettier never mixes tabs and
spaces, it would be a bug if it did. And there's no meaningful difference
_between_ tabs and spaces in Python either. Python has significant indent
stops, that's all.

Furthermore, prettier has a python plugin which does support tabs.

------
danpalmer
A bad formatter is worse than no formatter, and unfortunately YAPF proves this
out in my experience, being unstable, inconsistent, and tricky to configure.

Black however could fall into this category of worse than no formatter. On my
team we have a strong style guide with a lot of well-reasoned, detailed, and
consistent rules. One of the main differences to other style guides is that we
design our style to make review easier. One of the primary ways of doing this
is minimising diff noise.

While Black's vision is to reduce diff noise and design for easier review
through a consistent style, it creates more diff noise and has a less
consistent style than our style guide, and so we've had many discussions
internally about whether it's right for us.

I have no doubt that Black is better than weak/no style guide, and for open
source projects the automation it brings would absolutely be the right choice.
I just wish it was better at what it sets out to do.

Edit: to address some of the questions raised:

\- Yes Black does save time over code review picking on style details, but we
already have automated linters for most things we'd raise about style anyway,
which negates some of the time saving.

\- The easiest example of where Black differs from our style guide and falls
down on its promises is formatting lists/function calls/definitions.

For example:

    
    
      foo = [bar, bar]
    

When reaching the line length limit, we will turn this into:

    
    
      foo = [
        bar,
        baz,
        quux,
      ]
    

However Black will format this first as:

    
    
      foo = [
        bar, baz, quux
      ]
    

Only when it goes on a few more characters does it then format into the way
we'd go straight to. This means that there's more diff noise more of the time,
and when reading code there are 3 forms of this construction that one must be
aware of, rather than the 2 forms that we have, meaning the code is less
consistently formatted.

This is picky, yes, but the point of Black is to be picky, and in a team where
we can have a very good shared understanding of a style, and where we do
already have that style, Black is much less convincing.

~~~
4140tm
I have hated every single formatter I've tried, other than Black. It seems to
be the only one that's not just trying to put style into PEP8 compliance, but
also keep it readable and maintainable.

I'm also curious about the issues you've had with it.

~~~
jp_sc
The outout of Black is PEP8 compliant, just not what flake8 _think_ PEP8
mandates.

~~~
4140tm
Weird. I also use flake8 and the only mismatch between the two has been the
default line length of black, which I changed to 79. All is good now.

