Skip to content
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

Merged
merged 8 commits into from
May 13, 2018

Conversation

gaborbernat
Copy link
Member

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

@obestwalter
Copy link
Member

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?

@gaborbernat
Copy link
Member Author

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
Copy link

codecov bot commented May 12, 2018

Codecov Report

Merging #813 into master will increase coverage by <1%.
The diff coverage is 93%.

@@          Coverage Diff           @@
##           master   #813    +/-   ##
======================================
+ Coverage      95%    95%   +<1%     
======================================
  Files          11     11            
  Lines        2320   2321     +1     
======================================
+ Hits         2212   2213     +1     
  Misses        108    108

@obestwalter
Copy link
Member

obestwalter commented May 12, 2018

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.

Also, as a temporary safety measure, Black will check that the reformatted code still produces a valid AST that is equivalent to the original. This slows it down. If you’re feeling confident, use --fast.

... 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.

@obestwalter
Copy link
Member

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.

@gaborbernat
Copy link
Member Author

It's not perfect, but I think it still provides much value.

@obestwalter
Copy link
Member

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:

You probably noticed the peculiar default line length. Black defaults to 88 characters per line, which happens to be 10% over 80. This number was found to produce significantly shorter files than sticking with 80 (the most popular), or even 79 (used by the standard library). In general, 90-ish seems like the wise choice.

So I would also propose to keep the black default for that.

@obestwalter
Copy link
Member

Not a bug - missing (tricky) feature (string wrapping): psf/black#182

@gaborbernat
Copy link
Member Author

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.

@obestwalter
Copy link
Member

obestwalter commented May 12, 2018

It does some really weird things with strings though ...

It turns

fmt = (
    "%(asctime)s %(filename)s.%(funcName)s:%(lineno)d %(levelname)s: "
    "%(message)s"
)

into

fmt = (
    "%(asctime)s %(filename)s.%(funcName)s:%(lineno)d %(levelname)s: " "%(message)s"
)

It does not concatenate the strings again ...

@gaborbernat
Copy link
Member Author

Hmmm may require some manual one time mangling then. Probably fill in an issue for it though.

@obestwalter
Copy link
Member

See psf/black#205

Copy link
Contributor

@asottile asottile left a 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 :/

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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

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 :-)

@gaborbernat
Copy link
Member Author

@obestwalter take another look cleaned up manually few of the oddities, if there are any more you spot can do similarly

@asottile
Copy link
Contributor

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 🤷‍♂️

@gaborbernat
Copy link
Member Author

I'm personally not that pedantic about the single quote to consider worth the effort there.

@obestwalter
Copy link
Member

I also have a slight preference for single quotes, but don't mind either way, as long as it is consistent.

@gaborbernat
Copy link
Member Author

@obestwalter it now passed tests, let me know if you spot anything else 😄

@obestwalter
Copy link
Member

obestwalter commented May 13, 2018

I wish it was single quotes instead :/

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 initproj gets totally shot, which IMO is another black bug, as it actually changes the formatting of the string that will be outputted. In our case it is only an annoyance as the change in formatting does not affect the parsed config. It just looks really ugly now, but they can be formatted in normal strings anyway (I don't need a triple quoted string to create a test config with one or two line breaks), so I would suggest to reformat simple configs like:

    config = newconfig(
        [],
        """
        [testenv:py1]
        deps=pytest
    """,
    )

to:

config = newconfig([], "[testenv:py1]\ndeps=pytest")

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 :)

@asottile
Copy link
Contributor

asottile commented May 13, 2018 via email

@gaborbernat
Copy link
Member Author

Given tox is definitely not a web tool, I can get along with having ". As for the initproj we already dedent by default the code, so I think that's just fine.

@RonnyPfannschmidt
Copy link

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

@obestwalter
Copy link
Member

obestwalter commented May 13, 2018

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 bla = 'hello "world"' alone and reformats strings like blu = "hello \"world\"" to blu = 'hello "world"'

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.?

Copy link
Member

@obestwalter obestwalter left a 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]
""")
""",
)
Copy link
Member

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.

Copy link
Member Author

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.

Copy link
Member

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.

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"]
Copy link
Member

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 ...

["cmd2", "-f", "foo bar"],
["cmd3", "-f", "foo", "bar"],
]
)
Copy link
Member

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)])
Copy link
Member

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

Copy link
Member

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}}",
]
Copy link
Member

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')")
Copy link
Member

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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

loose the str() here.

- repo: https://github.com/pre-commit/pre-commit-hooks
sha: v1.1.1
rev: v1.2.3
hooks:
- id: trailing-whitespace
Copy link
Member

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.

- 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
Copy link
Member

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
Copy link
Member

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 :)

@obestwalter
Copy link
Member

obestwalter commented May 13, 2018

@asottile said:

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).

In general I agree, but I think in the context of a tox config test this is not a problem. If you accidentally type \b your test will fail and you'll fix the typo. The whitespace difference is also irrelevant in the context of those particular tests.

@gaborbernat
Copy link
Member Author

@obestwalter should be ready for merge now, 😄 as for doing the % to str.format I did it mostly by search, and pycharm suggestions

@obestwalter
Copy link
Member

as for doing the % to str.format I did it mostly by search, and pycharm suggestions

Wow. You've been busy then :) thanks for all the work you put in to whip that into shape.

getcontextname,
is_section_substitution,
parseconfig,
)
Copy link
Member

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.

Copy link
Member Author

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

Copy link
Member Author

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 👍

]
)
expected = [
"nosetests", " ", "-v", " ", "-a", " ", "!deferred", " ", "--with-doctest", " ", "[]"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

phew - thanks.

@obestwalter obestwalter merged commit 7a589ea into tox-dev:master May 13, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants