-
-
Notifications
You must be signed in to change notification settings - Fork 526
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add automatic code format enforcer - black #813
Conversation
Hi @gaborbernat, are you using this project already somewhere else and can share some experiences with it? A first glimpse over the diff, looks like it is doing a good job. I also think I could get used to that style. Is it stable? |
Was presented at PyCon lighting talks yesterday. Is marked as stable. I think it has been used internally at FB for a while, having a core Python developer as a creator should be a good enough guarantee. |
Codecov Report
@@ Coverage Diff @@
## master #813 +/- ##
======================================
+ Coverage 95% 95% +<1%
======================================
Files 11 11
Lines 2320 2321 +1
======================================
+ Hits 2212 2213 +1
Misses 108 108 |
I can't say I like the style it enforces, especially how parentheses are always on their own lines, but I get the argument that it produces the smallest possible difffs and most of that is a matter of getting used to anyway. http://black.readthedocs.io/en/stable/installation_and_usage.html#note-this-is-an-early-pre-release It's marked alpha.
... but that check puts my worries to rest. I will start using it in my own code that I am working with for a while. |
I stumbled over the first bug already. It does not correctly break lines in some cases. Will have a look if there is an issue for this already. |
It's not perfect, but I think it still provides much value. |
I just read the https://github.com/ambv/black#the-black-code-style and I have to say that I am convinced. I also agree with the thoughts about line length:
So I would also propose to keep the black default for that. |
Not a bug - missing (tricky) feature (string wrapping): psf/black#182 |
Eh I like what we have with 100 now myself. As for the later, maybe down the line it will be fixed and then the formatter will fix that too automatically. |
It does some really weird things with strings though ... It turns
into
It does not concatenate the strings again ... |
Hmmm may require some manual one time mangling then. Probably fill in an issue for it though. |
See psf/black#205 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wish it was single quotes instead :/
.pre-commit-config.yaml
Outdated
hooks: | ||
- id: trailing-whitespace | ||
- id: end-of-file-fixer | ||
- id: check-yaml | ||
- id: debug-statements | ||
- id: flake8 | ||
- repo: https://github.com/ambv/black | ||
rev: stable |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You'll want to pick a specific tag: https://pre-commit.com/#using-the-latest-version-for-a-repository
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed, and yeah I agree about the quotes; but at the end of day I prefer consistency over which of the two :-)
@obestwalter take another look cleaned up manually few of the oddities, if there are any more you spot can do similarly |
Another option would be to use autopep8 + double-quote-string-fixer (converts strings in the opposite directing of black) + a few other one off formatters to get basically the same deal 🤷♂️ |
I'm personally not that pedantic about the single quote to consider worth the effort there. |
I also have a slight preference for single quotes, but don't mind either way, as long as it is consistent. |
@obestwalter it now passed tests, let me know if you spot anything else 😄 |
Hey @asottile, if you are interested how this came to pass: I just stumbled over the issue dealing with this: psf/black#51 - there are a few very strong arguments why double quotes are the better choice. The TL;DR of the tipping point is: apostrophes (psf/black#75 (comment)). Regarding other tools: the more I look into black the more I get the feeling that this could become a standard that will save the community a lot of bike shedding. I really like the idea to approach the problem from the angle that code should be formatted in a way that maintainability and protection from stupid bugs is prioritized. For that goal it is doing stuff that "traditional" formatters won't touch and IMO that is a GoodThing. Prominently protecting us from the infamous: "Whoops there should actually have been a comma between those two strings in a list, where I moved an element from the end to the middle". @ambv also has a very clear vision, but is open to change his opinion if confronted with strong arguments (e.g. he also preferred single quotes first), so this looks like a very good project to go with and thanks to the AST checking safeguard, we do not have to be too worried that this first big reformatting PR will introduce some subtle bugs. The only problems I see atm are around the topic of strings, but they seem to be not too painful and will likely get better. I noticed that our way of creating these mini configs with
to:
Which is much more readable than even the default formatting anyway. I am going through the PR today and if there are no objections, I think we should whip this into shape together quickly as long as @gaborbernat has still his PyCon wings on :) |
the more I look into black the more I get the feeling that this could become a standard that will save the community a lot of bike shedding.
yapf started with exactly the same mentality, and is much more mature.
For that goal it is doing stuff that "traditional" formatters won't touch
true yapf / autopep8 don't even try here but that isn't to say that all
formatters don't:
- https://github.com/asottile/add-trailing-comma
- https://github.com/asottile/pyupgrade
The TL;DR of the tipping point is: apostrophes
For me it's less of a personal preference thing and more of an annoyance.
A good chunk of the python I write is for web development where double
quotes in strings are extremely common (html!). The linked comment above
happens way more frequently in the _other direction_ for me. It's also
contrary to nearly every style guide I've worked with (again, because web
development, but also because pressing the shift key is a slow and `"ERorr
prone"` operation).
config = newconfig([], "[testenv:py1]\ndeps=pytest")
Which is much more readable than even the default formatting anyway.
Having used this corner-cut myself before, I find it all too easy to typo
`\b` instead of `\n` whereas with multiline strings this isn't a problem.
Another note in your example is the two aren't equivalent -- there's a
whitespace difference (`textrwap.dedent` comes to mind).
Anyway, I'm not out here to change minds -- code formatters are some of my
favorite things and I think using more of them is a great step in the right
direction. Just wish @ambv's black didn't strongly prefer (in my mind) the
less convenient quotation style.
|
Given |
i just finished applying black to 2 of my projects along with pre-commit hooks while my quoting preference is also different, i consider it a straw-man argument, you fix it once, and then keep it consistent -> and consistency is more important there imho |
I understand your annoyance @asottile - it is very dependent on in which kind of universe your code lives - maybe that should really be something configurable in black and maybe it will be at some point to get those kind of projects on board (line lenght is configurable already after all). The way how black deals with quotes is definitely quite sane IMO - independent of preferences. It always tries to reformat the string in a way that you need the least amount of escapes. e.g. It leaves strings like As you seem o.k. with using black anyway as a step in the right direction and we have an implicit +1 from @RonnyPfannschmidt also, I would say let's just run with this for now. I'll finish reviewing this tonight then and merge it, so that new PRs coming in tomorrow at the sprint can already base on this, o.k.? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well, that was one of the most boring and at the same time terrifying PRs I ever had the honour to wade through. All in all I am quite pleased with what black does. There are a few instances where I am actively repelled when I see the result, but a lot of it is getting used to and the rest will be fixable by writing the code differently or in the occasional case where readability is too degraded by black there is always the # fmt: off | # fmt: on
wrapper.
Most of the comments are non actionable, where I just had to express my feelings :) - the other actionable ones are trivial.
Good job also on switching all strings to format as well. Which tool did you use for that?
[testenv:py1] | ||
""") | ||
""", | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looking at it closely it turns out that although what black does here looks awkward and in some cases as if it would change the actual output it really doesn't. It does the right thing and keeps the formatting of the resulting string exactly. So all o.k. on this front.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, the comma in this case is optional, but never changes the meaning.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was rather thinking that the line break introduced after the """
would introduce changes in formatting (in some cases - not this one, so the comment was placed not in a good example), but they don't.
tests/test_config.py
Outdated
assert config.option.force_dep == ["dep1==1.5", "dep2==2.1", "dep3==3.0"] | ||
assert ( | ||
[str(x) for x in config.envconfigs["python"].deps] | ||
== ["dep1==1.5", "dep2==2.1", "dep3==3.0", "dep4==4.0"] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wow - that looks really weird ...
tests/test_config.py
Outdated
["cmd2", "-f", "foo bar"], | ||
["cmd3", "-f", "foo", "bar"], | ||
] | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
oh dear ... I start wondering, if this isn't a bit too weird ... it will definitely need some getting used to reading stuff like this - but maybe it will also lead to expressing things like that differently, e.g. like:
result = [
["cmd1", "--foo-args=foo bar"],
["cmd2", "-f", "foo bar"],
["cmd3", "-f", "foo", "bar"],
]
assert x == result
(["-qq"], 2), | ||
(["-qqq"], 3), | ||
]) | ||
@pytest.mark.parametrize("args, expected", [([], 0), (["-q"], 1), (["-qq"], 2), (["-qqq"], 3)]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ugh - that one is really screwing up readability to me a lot.
Maybe we should deactivate it for these cases?
# fmt: off
@pytest.mark.parametrize('args, expected',
[
([], 0),
(["-q"], 1),
(["-qq"], 2),
(["-qqq"], 3),
])
# fmt: on
def test_quiet(self, args, expected, newconfig):
config = newconfig(args, "")
assert config.option.quiet_level == expected
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
scratch that - let's just see how it goes without any special casing this early in the game ... I guess it is all a matter of getting used to.
" ", | ||
"w[]ord", | ||
" ", | ||
"{posargs:{a key}}", | ||
] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yuck ...
tox/session.py
Outdated
tw.line("TOX_TESTENV_PASSENV: space-separated list of extra " | ||
"environment variables to be passed into test command " | ||
"environments") | ||
tw.line("TOXENV: comma separated list of environments " "(overridable by '-e')") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
needs manual concat.
tox/venv.py
Outdated
"command failed but result from testenv is ignored\n" | ||
" cmd: %s" % (str(err),)) | ||
"command failed but result from testenv is ignored\ncmd: {}".format( | ||
str(err) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
loose the str() here.
.pre-commit-config.yaml
Outdated
- repo: https://github.com/pre-commit/pre-commit-hooks | ||
sha: v1.1.1 | ||
rev: v1.2.3 | ||
hooks: | ||
- id: trailing-whitespace |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not necessary with black anymore, I guess.
.pre-commit-config.yaml
Outdated
- repo: https://github.com/pre-commit/pre-commit-hooks | ||
sha: v1.1.1 | ||
rev: v1.2.3 | ||
hooks: | ||
- id: trailing-whitespace | ||
- id: end-of-file-fixer |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
see above
@@ -16,6 +16,9 @@ | |||
.. image:: https://readthedocs.org/projects/tox/badge/?version=latest | |||
:target: http://tox.readthedocs.io/en/latest/?badge=latest | |||
:alt: Documentation status | |||
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg | |||
:target: https://github.com/ambv/black | |||
:alt: Code style: black |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I guess that is the case now :)
@asottile said:
In general I agree, but I think in the context of a tox config test this is not a problem. If you accidentally type |
@obestwalter should be ready for merge now, 😄 as for doing the |
Wow. You've been busy then :) thanks for all the work you put in to whip that into shape. |
getcontextname, | ||
is_section_substitution, | ||
parseconfig, | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
argh, now we're back to that thing, but tbh atm I don't care anymore. From now on it's just a question of reconfiguring whatever formatter we use.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah, maybe things will change in future with psf/black#204
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
stays as it is then 👍
tests/test_config.py
Outdated
] | ||
) | ||
expected = [ | ||
"nosetests", " ", "-v", " ", "-a", " ", "!deferred", " ", "--with-doctest", " ", "[]" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
phew - thanks.
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.
- https://github.com/ambv/black