
Black – Uncompromising Python code formatter - collinmanderson
https://github.com/python/black
======
camgunz
Against my better judgment I'll bite.

I super dislike black's formatting, and I think it's really rare to actually
see it in codebases. It wraps weirdly (sometimes not at all). I'd prefer to
use yapf, but last I checked it still crashes on "f-strings".

Here's a small example:

    
    
        basket.add({
            apple.stem
            for satchel in satchels
            for apple in satchel
        })
    

Black formats this as:

    
    
        basket.add(
            {
                apple.stem
                for satchel in satchels
                for apple in satchel
            }
        )
            
    

I've never seen Python code like that.

I totally believe using a formatter is good practice. Black is in a
challenging position of coming into a community with a lot of existing code
and customs, and I get that. But I also think that's an opportunity, rather
than having to guess at what is good, there's a wealth of prior art to look
at. I wish it had done this, rather than essentially codify the author's
style.

~~~
rav
I completely agree that black does not format all examples in a nice manner,
and your example is something I see pretty often. Whenever black adds too many
indentation levels and line breaks in what should be a simple-enough
statement, I simply refactor into multiple statements, e.g.

    
    
        stems = {
            apple.stem for satchel in satchels for apple in satchel
        }
        basket.add(stems)
    

I concede that without black it wouldn't have made sense to make that
refactoring, but since I _really_ want to use an autoformatter, and black is
the best autoformatter I have, I'd rather restructure my code slightly so that
I can just use black 100% all the time.

~~~
tedmiston
It's an interesting meta thought that using the autoformatter changes the way
you write your code. Not that that's implicitly a good or a bad thing, I just
find it interesting.

~~~
acdha
I think it’s under-appreciated when comparing tools like this. I’ve noticed
that a bit since adopting Prettier and Black and one thing I’ve noticed during
code review is that usually when I end up changing code structure to get
better results from the tool, it’s a refactor that I probably would felt like
I should have done but might have put off due to laziness even though it’s
really not that much work.

I’m kind of thinking of it as something like baking some exercise into your
day by putting a walk into your commute: the little nudge of not fighting the
tool on something minor means you don’t skip little things, and over time that
adds up more than it seems at first.

------
cjbprime
I often dislike autoformatter output too, but then I remember that while no-
one likes what the autoformatter does to _their_ code, everyone likes what the
autoformatter does to their coworkers' code, and then I chill out about it.

Having a standard is more important than the standard being excellent.

~~~
amelius
> Having a standard is more important than the standard being excellent.

Neither is very important, though. It's just formatting and your code will run
the same regardless.

~~~
adossi
You could say that about anything, though. Why use punctuation and
capitalization when typing forum comments? Its just syntax after all.

~~~
awinder
Why use many word when few word do trick

~~~
ben509
Because you don't know if they've done the trick. That's why natural language
is padded with extra words to add context and help rule out misunderstandings.
The grammatical rules of agreement are one mechanism to do this.

And you can see the phenomenon of over-abbreviation by reading a few debates
on twitter and repeatedly seeing, "how can you not understand what I
tweeted?!"

~~~
gooseserbus
FYI you're replying to a joke from The Office (US)
[https://www.youtube.com/watch?v=_K-L9uhsBLM](https://www.youtube.com/watch?v=_K-L9uhsBLM)

------
hprotagonist
The way you can tell that black is good is that everyone mildly dislikes a few
things about it, but they're usually different things.

That's usually a good clue that you've hit real middle-ground.

I blackify my projects once we hit 3 contributors.

~~~
rav
Why wait? I run black on all my new single-author projects.

~~~
hprotagonist
i have my personal tics about formatting that i enjoy. As long as it’s just
me, i’ll persist them.

~~~
rav
I can see the point of that. For me though, I just changed my personal tics to
match the tics of black :-)

------
rahimnathwani
DEP 0008 ('Formatting Code with Black') was accepted by the Django board last
week. They're going to wait until Black has a stable release before
reformatting all the code, as there's at least one thing they don't like about
how Black handles things.

[https://github.com/django/deps/blob/master/accepted/0008-bla...](https://github.com/django/deps/blob/master/accepted/0008-black.rst)

[https://groups.google.com/forum/#!topic/django-
developers/7G...](https://groups.google.com/forum/#!topic/django-
developers/7GZE3fIVVvo)

~~~
di
Seems like there are two things they want to see fixed:

> Several developers report that, in their experience, Black made code
> formatting worse and decreased readability. Concrete examples shown in the
> discussion were short lists, which Black reformats when they fit on a single
> line, and vertically aligned comments, which Black is unable to preserve.
> This is being addressed [0] in Black and is expected to be resolved before
> Black becomes stable.

[0]
[https://github.com/python/black/pull/826](https://github.com/python/black/pull/826)

------
_hardwaregeek
This is a case where I'm completely decided. Everybody should use an
autoformatter. The minimal benefit you get from custom formatting is
completely outweighed by the uniformity, the consistency and readability of
autoformatted code.

~~~
abtinf
I think a nontrivial portion of Go’s success can be attributed to having a
standard format and treating deviation as compiler errors.

It is immensely valuable to be able to look at any Go code, whether in the
toolchain, the standard library, or a random stackoverflow snippet, and not
have to think about formatting at all.

~~~
fwip
I think you're conflating two concepts a little bit - deviation from `gofmt`
isn't a compiler error, but lots of things (like unused variables or imports)
are. I think they're both great.

~~~
abtinf
You are corrrect. I guess I’ve learned to treat deviation from gofmt as error
because of the go vim plugin. It runs goimports on save, which fixes a bunch
of real errors (like unused imports).

------
CrLf
I've been using it for a few months now, but I don't really like it. It does
remove quabbles about formatting, but I've personally never felt that as a
problem and it just replaces them with constant frustration.

I think code formatting is very important for readability, and I think many
(subtle) choices about how to make a piece of code more readable are very
subjective. These types of tools are just incapable to make those choices
because they have no concept of intention.

And some rules make this painfully obvious even in less subjective cases. Eg:
black formats dictionaries into a single line if they fit one line, which
makes nested structures unreadable if they combine bigger and smaller sub-
dictionaries.

In the end, I don't have problems with other peoples' formatting choices; as
long as they are sufficiently consistent within their own style, which they
usually are, I can live just fine with them even when they go against how I'd
do things.

I do have problems with tools that reduce code readability for consistency's
sake and argue that these provide little benefit, and may even be detrimental
to code quality.

~~~
photonios
You could configure your IDE to re-format files into your favorite format and
just have a pre-commit hook that formats them back into the official format.
That's how I work. No arguments about style and formatting, yet I get to make
the code look how I personally prefer it.

~~~
a1369209993
No, we can't. My (and, by the sound of it, CrLf's) favorite format relies on
information that your pre-commit hook has _artificially removed_ from the
code. Eg:

    
    
      munge(gidget,
        thing1,thing2,thing3);
      cmplt(dtypeA,valueA,
            dtypeB,valueB);
    

(Most cases are more subtle (and thus less amenable to "oh, you just need to
build a complete static type checker into the formatter") than this, but I
wanted an obvious example.)

~~~
RussianCow
It seems like the signature of the functions should be different, especially
the second example. I would have written the cmplt function to take tuple
pairs:

    
    
        cmplt(
            (type_a, value_a),
            (type_b, value_b),
        )
    

That's much more clear about the relationship between each pair of values
either way, and would get formatted nicely by Black.

~~~
edflsafoiewq
No it wouldn't; black will put that all on one line if it can. The semantic
information in vertical space is lost.

A better example is a matrix laid out as a grid, which auto-formatters always
destroy

    
    
        mat3x3(
             0,  a, -b,
            -a,  0,  c,
             b, -c,  0,
        )

~~~
a1369209993
To be fair, I suspect RussianCow would write that as something like:

    
    
      mat3x3(
        rowvec3( 0, a, b),
        rowvec3(-a, 0, c),
        rowvec3( b,-c, 0),
        )
    

Which is probably better, especially with tuples instead of struct{Scalar[3]}.
Doesn't fix

    
    
      mat3x3(( 0, a, b),(-a, 0, c),( b,-c, 0))
    

, though.

------
p0cc
I use black because it is idempotent. Google's yapf lacks this property.

Edit: Previous discussion:
[https://news.ycombinator.com/item?id=17155048](https://news.ycombinator.com/item?id=17155048)

~~~
strangemonad
Unrelated: thank you for using “idempotent” correctly. Too many people use it
to mean referential transparency or having a functionality property

~~~
globuous
wooow, so can we think of Black as outputing a projection of your source code
in some space ?

~~~
mlevental
wut? idempotent is any operator T such that T^2=e the identity. for example
ring elements can be idempotent
[https://en.m.wikipedia.org/wiki/Idempotent_(ring_theory)](https://en.m.wikipedia.org/wiki/Idempotent_\(ring_theory\)).
it's not just characteristic of linear operators.

~~~
CarlsJrMints
Idempotence means T^2=T. Are you thinking of involution?
[https://en.wikipedia.org/wiki/Involution_(mathematics)](https://en.wikipedia.org/wiki/Involution_\(mathematics\))

~~~
mlevental
you're right i'm wrong. but my saving grace is that they're related
[https://en.wikipedia.org/wiki/Idempotent_(ring_theory)#Relat...](https://en.wikipedia.org/wiki/Idempotent_\(ring_theory\)#Relation_with_involutions)

------
marliechiller
I've been using this for a couple of weeks and its a been really nice to
remove the constant mental overhead of structuring code. it also makes you
think about structuring functional blocks into more manageable, bite-sized
chunks which is easier to understand. 10/10 would recommend

~~~
jhrmnn
Yes, the side effect of using black seems to be a more reasonable factoring
within function bodies.

------
yellowapple
Played around with it in the sandbox and immediately disliked its insistence
on putting every item in a sufficiently-long array on its own line. For
example, something like:

    
    
        foo = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ]
    

Black formats it to something more like:

    
    
        foo = [
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10,
            11,
            12,
            13,
            14,
            15,
            16,
            17,
            18,
            19,
            20,
            21,
            22,
            23,
            24,
            25,
            26,
            27,
            28,
            29,
            30
        ]
    

That's, in my not-so-humble opinion, absolutely atrocious. Compare with how
Emacs formats if it I press M-q (with python-mode and EditorConfig):

    
    
        foo = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
                19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ]
    

More readable (again, IMO) and way more compact.

The default line length of 88 also seems weird, but at least that's readily
configurable to my preferred 80.

~~~
jsmeaton
Because it’s optimised for producing the smallest diff once it’s already been
formatted and a change is made.

If you add a single item to your preferred style, the entire thing has to be
reflowed.

~~~
yellowapple
Only if I add an item in the middle. If I'm always appending, then only the
last line will show a diff, and said diff will be for the added entry.

Even in a case where I need to add an item in the middle, the diff will -
again - only start where I actually added an item, and any human can readily
see that the rest of the downstream diffs were from the reflow.

Of course, it'd be even better if diff tools were more aware of the
format/language of the code being diff'd, at which point it'd be able to say
"new element added to foo" instead of reporting on a bunch of reflowed lines.

------
timothycrosley
Black is amazing. I've added it to all my work projects and will be adding it
to all my personal projects over time. My own opinion is that black is the
future of Python formatting and it's a long time in coming. I disagree with
many of the ways it formats things, but I mostly am just ecstatic to no longer
have to discuss these things and just write code. If you are an isort user:
isort's primarily goal for the next release is to add a mode that gaurentee's
100% compatibility with black (it can be achieved currently via config
options). And of course, I'll be formatting the isort project itself using
both isort and Black.

------
infecto
I have just started using it and love it. It sounds funny but while formatting
is not always a deal breaker it still kills me for 1) readability and 2) the
faith that when someone reads the code base later one they know I was not an
idiot.

I know 2 is kind of subjective but when I look at someone elses code and I see
obvious mistakes against pep8 I start judging both the person and the code
harshly. Perhaps unfair but for the very simple pep8 rules I see it as someone
who is not as well versed in Python and perhaps does not care about their code
as much.

Overall I just concede that consistency is better than everyones personal
tastes. For a startup I think you can get by with just some custom linting but
in a larger org I find it much harder to agree on a consistent format unless
you are a Python first org. Much easier just to roll Black into the project
and go with it.

~~~
goostavos
That's pretty lazy thinking, imho. "Person x doesn't care about their code
because they didn't use the formatting I like"

Worrying about or judging code based on PEP8 is missing the forest for the
trees[0]

[0] [https://www.youtube.com/watch?v=wf-
BqAjZb8M](https://www.youtube.com/watch?v=wf-BqAjZb8M)

~~~
frosted-flakes
It's not that, it's that they use _inconsistent_ and non-standard formatting.

For example, in JavaScript, there is always a space before a function's
opening curly bracket. This is pretty much a global standard, and it's rare to
see code that doesn't follow this rule.

However, I'll occasionally see code on Stack Overflow that randomly excludes
these spaces. It honestly makes it so much harder to read, and I'm less
willing to put in the effort to help them, because they didn't even go to the
effort of properly formatting their code. Inconsistent indentation especially
kills me because it makes code impossible to read.

~~~
cuddlecake
Technically, one could spend his life learning and perfecting JS or Python
skills, without ever learning how other people format code. If you don't have
a reference, you cannot align.

Also, imagine blind people coding. I imagine they have a completely different
stance on how code should be formatted.

------
fredley
We use Black in a pre-commit hook for all our python code. It makes legibility
and formatting a non-issue in the team. Yes it can look strange at first if
you're not used to it, but after a while it makes formatting invisible (and
it's odd reading non-black python). Would recommend.

~~~
mlevental
how do you do this? do you have a jenkins server running that does the
formatting? i would love to set this up because while i use black religiously
i cannot for the life of me convince my boss get in the habit of using it
(which is crazy because your commits are always fighting on whitespace).

~~~
guitarbill
Use pre-commit [0] so people can run it client side for quick feedback, and
then use whatever CI you have (Jenkins, Travis, Circle, Azure) to enforce
this. The important parts are the majority of people agree to do it, and that
you have CI to be the "bad cop"/fall guy so it never becomes personal.

(edit: black has pre-commit support [1], and it's easier than setting up and
maintaining your own hooks IMO)

[0] [https://pre-commit.com/](https://pre-commit.com/)

[1]
[https://github.com/python/black/blob/master/README.md#versio...](https://github.com/python/black/blob/master/README.md#version-
control-integration)

------
ed_balls
I use black every day. It's pretty good. The hours you save on pointless
arguments e.g. ' or " is better as default for strings. I wish it'd come with
standard python distribution `python fmt`

~~~
brootstrap
yeah, someone above mentioned that with Go as the example. It's pretty nifty
in some cases but think there are two sides to the story. I know folks who
write lovely python code everytime. I know others at my gig who even after 3
years are not putting spaces after equals sign (and other PEP/flake8 blunders)
and every PR is littered with syntactic errors. The code formatter is
brilliant for this case.

~~~
anoncake
I don't think making code written by hacks look like code written by a
competent programmer is a good thing.

~~~
misterdoubt
Making the code more clear to read helps its quality come through. Or its lack
thereof.

~~~
anoncake
Nothing stops a reviewer from reformatting the code before reading it
(probably using an autoformatter).

But I'm not sure if making the code easier -- and thus faster -- to read is
necessarily a good thing. If the brain parses and analyzes the code in
parallel, making it harder to parse could give the analyzing process more time
and thus make the review more thorough.

Of course, nothing stops a reviewer from being thorough either way. But making
it the path of least resistance makes it more likely.

------
haraball
Beside the benefit that black removes any discussion regarding formatting, my
favourite benefit otherwise is the speed-up it yields by having it run
everytime I save a file. I don't have to care about line lengths or
single/double quotes or stuff like that anymore, since black will fix it for
me anyway. And if black fails to trigger, it means there is something wrong
with my code somewhere.

This is what I've stuffed in my VS code settings:

    
    
        "python.formatting.provider": "black",
        "editor.formatOnSave": true,

------
jupp0r
> Black is the uncompromising Python code formatter. By using it, you agree to
> cede control over minutiae of hand-formatting. In return, Black gives you
> speed, determinism, and freedom from pycodestyle nagging about formatting.
> You will save time and mental energy for more important matters.

I run into this philosophical debate at work. In my mind, I don't care much
what the resulting code looks like as long as

\- it's somewhere in the reasonable spectrum of readablility

\- it's consistent and unambiguous

\- it never fails for a syntactically valid source file (if it's doing
something for syntactically invalid source files, even better, formatting
helps me find the error)

There are other opinions though that emphasize minimizing diffs or extensive
customization to fit somebody's favorite style (I'm looking at you, rustfmt).
Black seems to be right down my alley.

------
Kpourdeilami
We have been using this for almost 7-8 months and even though I don't
personally like the style of it very much, it has helped keep everything
consistent. You can set it up as a pre-commit hook to automatically format the
code too

------
andrewljohnson
We recently started using a lot of auto-formatters across our
Python/iOS/Android code, as the team has grown (there are 17 people touching
code at the company now).

I like auto-formatting, because it makes PRs less stressful to commit, and
makes review comments more focused on stuff that actually matters. How exactly
the code gets formatted is not something I care much about, just that it
happens consistently, and I don't have to think about it.

We use pre-commit with Black and other formatters, such that it formats the
code, warns you stuff changed, prevents the commit, and makes you recommit
with the formatting patch included.

~~~
fwip
Because pre-commit can be tough to google sometimes, depending on your search
history, here's the direct link: [https://pre-commit.com/](https://pre-
commit.com/)

~~~
fizzybeetle
I assumed the poster meant the git concept of pre-commit hooks, which is just
a shell script - [https://git-scm.com/book/en/v2/Customizing-Git-Git-
Hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks)

~~~
andrewljohnson
Your parent is correct. Here's our pre-commit config too FWIW:

    
    
      more .pre-commit-config.yaml
        repos:
          - repo: https://github.com/pre-commit/pre-commit-hooks
            rev: v2.1.0
            hooks:
              - id: end-of-file-fixer
              - id: check-json
              - id: check-yaml
      - repo: https://github.com/asottile/reorder_python_imports
        rev: v1.3.4
        hooks:
          - id: reorder-python-imports
            args: [--application-directories=gaia]
            language_version: python3
      - repo: https://github.com/ambv/black
        rev: stable
        hooks:
          - id: black
            language_version: python3
      - repo: local
        hooks:
          - id: eslint
            name: eslint
            entry: ./frontend/node_modules/.bin/eslint --fix
            language: node
            language_version: system
            files: \.(js|jsx|ts|tsx)$
      - repo: https://github.com/prettier/prettier
        rev: "1.15.3"
        hooks:
          - id: prettier
            files: \.(yml|yaml|md|json)$
            language_version: system

------
alexhutcheson
Feature request: Add a flag that allows you to specify which lines to format.

I'm an auto-formatting true believer, but I _hate_ doing code reviews where
the author has run a formatting tool that introduced diffs all over parts of
the file that they didn't actually touch. It makes it really hard to review
the actual change, and you have to worry about missing something.

With something like ClangFormat's '\--lines' flag, you can configure the tool
to only modify the lines that the author actually changed. This removes most
of the pain that comes with adopting an auto-formatting tool, and your
codebase will gradually converge to the fully auto-formatted state over time.

This also makes it easier for to introduce improvements to the formatting tool
itself, because the improvements won't immediately force a bunch of diffs on
code that was already "blessed" by the tool.

~~~
weberc2
Sounds like you're using it wrong. The autoformatter is for the whole repo,
not for individual contributors. The point is that the whole repo has the same
style, so you should only ever get diffs on the lines that were changed or the
first time you run the autoformatter on the repo (and then you shouldn't be
making manual changes that will be hidden amid the autoformatter noise).

~~~
alexhutcheson
Most larger orgs/projects aren't going to be willing to reformat all the code
in their repo in one big bang. Regardless of what promises the tool claims to
make, you need to be concerned about behavior changes or breakages, and most
projects don't have high enough test coverage to cover everything. Depending
on the size of your repo, it might not even be technically possible to make
this change all at once. It's also much harder to get organizational buy-in on
"let's change all existing code in one swoop" vs. "let's require all new code
changes to be formatted using this tool".

As I mentioned above, formatting only the diffs also removes most of the pain
of any changes to the formatting tool itself that aren't diff-stable.

~~~
weberc2
I shouldn’t have said repo, but rather some agreed upon unit of code. It could
be a single package or file as long as all contributors touching that file
adhere. You should not use black for any unit of code that you can’t get buy-
in on. Black is a technical tool; it doesn’t solve political problems.

------
dylrich
"Gofmt's style is no one's favorite, yet gofmt is everyone's favorite"

Happy Black user over here!

------
PhilipTrauner
Since I've started using black as a pre-commit hook and an editor extension, I
have noticed that I tend to use inline-if expressions and lists comprehensions
much more liberally, because I do not have to worry about formatting all the
time. Begone temporary variables!

------
skybrian
This is a trend that I believe started with Go's code formatter, but such
formatters differ in how much reformatting they will do.

Go's formatter adjusts whitespace within a line and will add or remove blank
lines, but it doesn't change line breaks and has no opinion on the maximum
length of a line. Other formatters work differently.

------
jaimebuelta
There are some things in Black that I don't particularly like, for example the
preference for double quotes over single quotes...

But the part that drives me crazy is this...

    
    
        # in:
    
        ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
    
        # out:
    
        ImportantClass.important_method(
            exc, limit, lookup_lines, capture_locals, extra_argument
        )
    

instead of

    
    
        ImportantClass.important_method(exc, limit, lookup_lines, 
                                        capture_locals, extra_argument)
    

which to my eyes is way more readable and understandable. I understand what in
some corner cases (if the call is too long that all arguments require its own
line) it may be weird, but in those cases, it is showing that you try to do
something strange in the first place (too long of a method name or too many
elements in the call)

------
roma1n
How do you enforce the use of a formatter in a project -- pre-commit hook?
pre-receive hook? both? And is there a convention to put a specific dotfile at
the project root to hint at your IDE/editor that it should use a certain tool
for automatic formatting?

~~~
im_new_here
CI runs a linter and fails the build if the output is non-empty. PRs can't be
merged unless the build passes on the branch.

~~~
raverbashing
Yeah no because this changes the code and does not merely complain

~~~
IanCal
One, that shouldn't matter on CI anyway. Two, you can tell black to just print
the difference with --diff and tell it to just check the files with --check.

~~~
raverbashing
Yeah, true, though ideally you would do it before the commit so you wouldn't
have one extra lint commit per code commit

------
neuronexmachina
My current "problem" with Black is actually a 5-year-old bug in how pylint
checks for bad-continuation issues with hanging indentation. Sure, you can
ignore the pylint rule, but I imagine pretty much everybody who tries to use
black and pylint on the same codebase runs into this issue:

* [https://github.com/PyCQA/pylint/issues/289](https://github.com/PyCQA/pylint/issues/289)

* [https://github.com/python/black/issues/48](https://github.com/python/black/issues/48)

------
dev_dull
Every language should just have a go fmt. Go showed us a better way. All
languages should copy this design.

------
genmon
I love black: formatting isn't a _big_ thing to think about, but it's always
there. Until black. For [current project] it's hooked into VS Code as the
default formatter, and (inspired by simonw) we've incorporated a black check
into the test suite. It's simple:

[https://github.com/simonw/sqlite-
utils/blob/master/tests/tes...](https://github.com/simonw/sqlite-
utils/blob/master/tests/test_black.py)

------
2Ccltvcm
Black is essential for maintenance of Pandas code which uses method chaining.

If you use Pandas you should be using method chaining and therefore also
black.

~~~
tda
However the pandas source is not blackened, and I really miss not be able to
just fix all formatting issues while working on a PR. After just a few months
I am so used to black it just feels weird to not have it everywhere

------
inglor
And in Stack Exchange's "The Workplace", people are complaining that their
employees strongly object to Black
[https://workplace.stackexchange.com/questions/136742/virulen...](https://workplace.stackexchange.com/questions/136742/virulently-
against-code-formatting)

~~~
ixtli
I have some issues with aesthetic decisions used in Black but the degree of
head-nodding on the top answer in the SE post you linked is really
disconcerting. The person basically says "well you're the boss so you should
kindly remind your employees that its your way or the highway" in several
different sentences.

It's pretty disturbing that people think this is how a manager behaves. Turns
out there are reasons beyond aesthetics that people should apply strict code
formatting practices.

------
collinmanderson
I like the idea of auto-formatting code, like go does.

Though I think I prefer autopep8

~~~
photonios
Black goes much further than autopep8. Black is an auto-formatter. autopep8
tries to automatically fix PEP-8 issues.

------
gubbrora
I initially used autopep8 and had set vscode to autoformat region on paste.
When I changed to black I started getting error messages about region format
not supported everytime I pasted.

As I mainly use other languages, with formatters with working region support,
I went back to autopep8 so I could leave it format region enabled.

~~~
justwalt
Doesn’t it cache everything that it’s formatted, meaning you could paste +
save to achieve the same effect? I had the same annoyance as well but stated
doing it this way and never had any complaints.

------
quietbritishjim
Auto formatters are great but the problem with Black is that Python is
fundamentally incompatible with them, at least if you're only willing to
insert whitespace. For example a line of code like this:

    
    
        x = y[1]['a'] + z[2]['b']
    

can be broken like this in Black (if it's over the line length limit):

    
    
        x = y[1][
            'a'] + z[2]['b']
    

But it needs brackets inserted so that it can be formatted something like
this:

    
    
        x = (
            y[1]['a']
            + z[2]['b']
        )
    

You can argue the formatting I've chosen e.g. whether the binary operator
should go on the previous line (the above line is what PEP 8 suggests). But
surely it's clear that breaking in the indexing bracket is atrocious.

~~~
konschubert
Black does add brackets in some situations.

~~~
quietbritishjim
Frankly, that is a really annoying comment to make. Can it add brackets in the
particular situation I just said? If so, I'd actually be interested, because
it's while since I last checked so it could will have changed. But if not,
you've made it look like my comment's invalid for no reason.

It reminds me of the last time Black came up on a Hacker News. I posted the
same objection (but hypothetically) and the actual creator of Black replied
with a comment along the lines of "you should check for yourself before making
a comment like that". By the time I finally did check, the discussion had died
down (like this one now has) and not many people saw the reply. As the
creator, he must have known that my objection was correct but he posted a low-
effort misleading comment that invalidated it. It doesn't give me a great
feeling about the project. I realise you couldn't have known that happened but
you can see why I find your reply so annoying.

------
tlrobinson
Automatic code formatting should be the norm in programming. Once you get used
to format-on-save and CI enforcement (especially on a team) it's hard to
imagine going back to having to think about how to format your code, or
pestering collaborators to follow some nickpicky code style guide.

------
john-radio
I like black. As hprotagonist pointed out, everyone has a few things about it
they don't like. What I like to do:

    
    
        $ black --skip-string-normalization my_python_script.py
        $ git add --patch my_python_script.py
    

Then I accept or reject all its suggestions (other than the string
"normalization" idea which is not our convention) on a case-by-case basis,
then `git commit; git reset HEAD --hard`.

~~~
crehn
Seems like a lot of work just to satisfy some arbitrary aesthetic sensitivity.

Especially when working in teams, I couldn't care less about the style itself.
As long as it's consistent, super easy to adhere (`black .`) and fairly
readable, I'm happy.

------
msluyter
If you use PyCharm, you can use cmd-alt-L to autoformat a file (and also
reorder/fix imports). By default, I believe it just uses the pep8 standard,
which I find generally sufficient, but you can evidently integrate Black via:

[https://black.readthedocs.io/en/stable/editor_integration.ht...](https://black.readthedocs.io/en/stable/editor_integration.html)

~~~
schemathings
FWIW gg=G formats in vim (whole doc), with lots of variations available ..
more examples: [https://stackoverflow.com/questions/506075/how-do-i-fix-
the-...](https://stackoverflow.com/questions/506075/how-do-i-fix-the-
indentation-of-an-entire-file-in-vi)

------
brockhaywood
pre-commit with black and flake8 makes for a pretty low overhead setup to have
a pretty consistent codebase

------
dethos
Black is an awesome tool. You might not like one or two of their decisions,
but it completely eliminates discussions related to taste on a given team and
the fact it is not configurable is its biggest value proposition.

------
dewiz
I hope to have something similar for every programming language, no need for
configurations, no petty discussions on this anymore.

    
    
        If you're paid by the line of code you write
    

:-)

------
yingw787
I haven't used Black in production; does it work well with a fully explicit
.pylintrc file, or does it do its own thing? I think interop with Pylint would
make or break such a tool for me.

------
klyrs
Neat. I've been using an autopep8 pre-commit hook for a while, even though I
kinda hate it (but nobody complains about noncompliant code anymore). I'll
have to give this one a shot

------
davidjhall
Why on earth would it convert this:

printable_chars = { 33, 34, 35 [...and another few hundred ]

to printable_chars = { 33, 34, 35 [...and another few hundred lines ]

~~~
crooked-v
Those look the same to me.

~~~
pritambaral
Perhaps your parent failed to add double-newlines and HN's formatting ate
their newlines, but notice the extra word "lines" at the end.

------
pletnes
How do people use autoformatters in CI pipelines? I dislike the fact that
precommit hooks have to be set up for each git clone. Is there a better way?

~~~
grinchygrinch
At my previous job, "Formatting" task was the first thing pipeline did. It was
really simple - it ran the same "make format" target you could run locally,
except it was configured in a way to fail if running "git diff" afterwards
resulted in any changes when running on the build server (git diff -s --exit-
code). Of course, when this failed, none of the other tasks in a pipeline ran
so it forced you to format your code correctly if you wanted to see build
results. You could just commit the next commit with "formatting" message but
the idea was to just change the history since commiting was happening on dev
branches - only when everything in the pipeline passed things could be merged
on stable branches.

------
misiti3780
i have been using the black integration with vscode and i have come to the
conclusion that:

1\. black is not perfect, but it is pretty great

2\. vscode is a much better IDE than Atom

------
macawfish
I started using black with one of my personal projects. Now I find myself
wishing if was set up in every other python project I work on!

------
jdoliner
I sincerely hope that adding this to your project is referred to as "taking
the Black." Too good an opportunity to miss.

------
josh2600
My friend (who played keyboard in my jazz quartet until he moved to Europe) is
the author of this! It's super cool.

Hi Lukasz!!

------
ta1234567890
Is there anything like this for ruby? Would love using it as a plugin for
sublimetext, atom or visual studio.

~~~
anonova
[https://github.com/testdouble/standard](https://github.com/testdouble/standard)

------
danbrooks
Black is my favorite auto formatter. I use it for python scripts and
blackcellmagic for jupyter notebooks.

------
laktak
More languages should have this. Does anybody know of a c# autoformatter that
works on Linux?

------
ynnn
The ford logo is a nice touch.

~~~
logicallee
For anyone who doesn't get it, the name and logo comes from the famous story
where Henry Ford, maker of the Model T -- one of the first affordable
automobiles, because it was made on an assembly line -- said "Any customer can
have a car painted any color that he wants so long as it is black." This quote
and assembly-line idea translate into the branding of this project. (The
project logo is visually similar to the modern Ford company logo, but with the
word Black instead of Ford.)

------
jordic
perhaps the only missing feature (like in flake) is to be able to bypass the
formatter with a comment (to be confortable with edge cases, where readavility
matters)

something like: # nofmt

~~~
jsmeaton
This exists now :)

------
nihil75
Let me know when it's available as a Vim plugin.

~~~
lvh
It’s been available that way for over a year:

[https://github.com/python/black/blob/master/plugin/black.vim](https://github.com/python/black/blob/master/plugin/black.vim)

------
hawaiian
>uncompromising

But does it have an #ignoreformatter directive?

~~~
syockit
Yes.

    
    
      # fmt: off
      unformatted code goes here
      # fmt: on

------
mychael
Having worked in Python for many years, I can tell you that nobody actually
writes code that looks like Blacks formatting.

It's a major step backward for the Python community.

~~~
weberc2
Having worked in Python and other languages for many years, I can tell you
that 1) this doesn't matter and 2) many of the ways people write Python are
much uglier than the conventional formatting in other languages. Most notably:

    
    
        this_is_my_very_long_function_name_and_here_come_the_args(self,
                                                                  foo,
                                                                  bar,
                                                                  baz)

~~~
rayrrr
Yay! This. Where else do we recommend arbitrary indentation levels? Nowhere.
So...which is the "foolish consistency" then? Is it consistent indentation
rules? Or consistently lining up arguments with function/method opening
parentheses?

------
AceJohnny2
Bikeshedding: The Thread.

