21 ms·
Black – Uncompromising Python code formatter
- collinmanderson 7y agoI like the idea of auto-formatting code, like go does. Though I think I prefer autopep8
- photonios 7y agoBlack goes much further than autopep8. Black is an auto-formatter. autopep8 tries to automatically fix PEP-8 issues.
- marliechiller 7y agoI'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 7y agoYes, the side effect of using black seems to be a more reasonable factoring within function bodies.
- ed_balls 7y agoI 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 7y agoyeah, 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 7y agoI don't think making code written by hacks look like code written by a competent programmer is a good thing.
- misterdoubt 7y agoMaking the code more clear to read helps its quality come through. Or its lack thereof.
- anoncake 7y agoNothing 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.
- p0cc 7y agoI 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 7y agoUnrelated: thank you for using “idempotent” correctly. Too many people use it to mean referential transparency or having a functionality property
- globuous 7y agowooow, so can we think of Black as outputing a projection of your source code in some space ?
- thaumasiotes 7y agoOff the top of my head, sure, you could think of things that way, but I don't see that you get a lot out of that framing.
- mlevental 7y agowut? 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 7y agoIdempotence means T^2=T. Are you thinking of involution? https://en.wikipedia.org/wiki/Involution_(mathematics) https://en.wikipedia.org/wiki/Involution_(mathematics)
- mlevental 7y agoyou're right i'm wrong. but my saving grace is that they're related https://en.wikipedia.org/wiki/Idempotent_(ring_theory)#Relation_with_involutions https://en.wikipedia.org/wiki/Idempotent_(ring_theory)#Relat...
- hprotagonist 7y agoThe 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 7y agoWhy wait? I run black on all my new single-author projects.
- hprotagonist 7y agoi have my personal tics about formatting that i enjoy. As long as it’s just me, i’ll persist them.
- rav 7y agoI can see the point of that. For me though, I just changed my personal tics to match the tics of black :-)
- cuddlecake 7y agoI would do the same on any JS project with prettier. I write some garbage-formatted code, press ctrl-s, and the code is formatted automatically. Even on a single-dev project, I would take a config and just put it there for the convenience it provides me. If I ever were to code python again, I would probably also use black.
- _hardwaregeek 7y agoThis 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.
- rurban 7y agoI also switched to mandatory clang-format for a big C project of mine last month. Just the PR hooks and linter integration into github not yet. Saves away a full round of nit picking.
- abtinf 7y agoI 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.
- masklinn 7y ago> treating deviation as compiler errors. That's not the case at all. The Go compiler treats an arbitrary few lint issues as compiler errors (e.g. unused imports), code which is not gofmt-formatted isn't a compiler error.
- fwip 7y agoI 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 7y agoYou 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).
- 7y ago
- brockhaywood 7y agopre-commit with black and flake8 makes for a pretty low overhead setup to have a pretty consistent codebase
- Kpourdeilami 7y agoWe 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
- roma1n 7y agoHow 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?
- weberc2 7y agoWe are using a pre-commit hook but I also have an on-save hook in my editor. Further, we also have a CI job that runs `black --check` which returns 1 (failing the build) if the files weren't completely formatted with black. In Go, the convention is that everyone's editor runs gofmt on change, and because the convention is so strong, that's usually enough (although many larger projects also have a CI job similar to the one described above). Having used both extensively, my biggest grievances (in order) are that there aren't more editors that with good on-save support, that black is relatively slow (compared to gofmt), and that black isn't more opinionated and less configurable.
- im_new_here 7y agoCI 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 7y agoYeah no because this changes the code and does not merely complain
- IanCal 7y agoOne, 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 7y agoYeah, true, though ideally you would do it before the commit so you wouldn't have one extra lint commit per code commit
- ta1234567890 7y agoIs there anything like this for ruby? Would love using it as a plugin for sublimetext, atom or visual studio.
- anonova 7y agohttps://github.com/testdouble/standard https://github.com/testdouble/standard
- klyrs 7y agoNeat. 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
- CrLf 7y agoI'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.
- skybrian 7y agoAre you sending unfortunate examples upstream? It's still beta, so it can be improved somewhat.
- CrLf 7y agoNo, because I believe this is fundamentally unfixable. It's not a matter of changing this or that behavior, it's a matter of (apparent) formatting inconsistencies being important to convey intention and distinguish more important from less important bits. In the example I mentioned, I may sometimes choose to put a small dictionary initialization into a single line if it's just a detail, or may split it into multiple lines if it's important enough for someone reading the code to pay attention to it before going further. This simply cannot be decided by an automatic formatter without it knowing the code's purpose which, for now, requires a human brain. Someone mentioned elsewhere that automatic formatters remove the cognitive load of formatting code, but I argue that load is an intrinsic part of programming, because it is (for the most part) the effort of communicating to the next person that comes along.
- nihil75 7y agoLet me know when it's available as a Vim plugin.
- lvh 7y agoIt’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
- misiti3780 7y agoi 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
- fredley 7y agoWe 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 7y agohow 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 7y agoUse 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#version-control-integration https://github.com/python/black/blob/master/README.md#versio...
- devvesa 7y agoBlack's README explains how to do it: https://github.com/python/black#version-control-integration https://github.com/python/black#version-control-integration
- c0un7d0wn 7y agoSee https://github.com/shosca/django-sorcery/blob/master/Makefile#L44 https://github.com/shosca/django-sorcery/blob/master/Makefil... for example Run that target as part of the test
- camgunz 7y agoAgainst 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 7y agoI 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 7y agoIt'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.
- setr 7y agoEvery metatool you use does that - syntax highlighting, linters, formatters, ide’s, etc You always end up adapting to the tool, while adapting the tool to you Until you oneday reach a perfect harmony with your tool... until you introduce another one, and the equilibrium must once again be found. Also of note, this is a general principle/behavior (eg you and your furniture..!)
- 2Ccltvcm 7y agoBlack 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 7y agoHowever 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
- skybrian 7y agoThis 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.
- cjbprime 7y agoI 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 7y ago> 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.
- deleted 7y ago[deleted]
- adossi 7y agoYou could say that about anything, though. Why use punctuation and capitalization when typing forum comments? Its just syntax after all.
- awinder 7y agoWhy use many word when few word do trick
- mrmonkeyman 7y agoYeh y ndeed
- ben509 7y agoBecause 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?!"
- inglor 7y agoAnd in Stack Exchange's "The Workplace", people are complaining that their employees strongly object to Black https://workplace.stackexchange.com/questions/136742/virulently-against-code-formatting https://workplace.stackexchange.com/questions/136742/virulen...
- melling 7y agoSomeone is always going to complain.
- ixtli 7y agoI 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.
- acdha 7y agoYou can find someone who’ll complain about anything. You have to evaluate whether they’re actually complaining about something valid or just reacting to change. In the example cited, notice how insubstantial the complaints are? That’s a dead giveaway for someone who is reacting rather than thinking rationally about the goals and benefits. An important distinction to remember here is that we’re talking about something which is safe, fully automatic, and easily integrated into most editors, so the effort to follow it is a few seconds the first time you set it up. I’ve generally found three classes of reaction to standardizing formatting, linting, and similar style checks: most people just roll with it, some people work through the initial “this is different!” reaction and realize how much easier consistency makes things (it’s been months since code review wasted time on formatting!), and a much group never get over it. I’ve only seen that a couple of times in a couple of decades and those were people who were net losses overall because this was just a symptom of a larger unwillingness to work well with others. The same guys refused to test their code, committed syntax errors or failed merges, wasted time reporting problems due to incredibly hacked up local build environments, etc. The important thing to remember is that those are a vanishingly small part of the community and I would make policy around them only to the extent of figuring out how to keep them from dragging your project down.
- macawfish 7y agoI 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!
- ynnn 7y agoThe ford logo is a nice touch.
- logicallee 7y agoFor 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.)
- dylrich 7y ago"Gofmt's style is no one's favorite, yet gofmt is everyone's favorite" Happy Black user over here!
- genmon 7y agoI 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/test_black.py https://github.com/simonw/sqlite-utils/blob/master/tests/tes...
- jupp0r 7y ago> 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.
- dev_dull 7y agoEvery language should just have a go fmt. Go showed us a better way. All languages should copy this design.
- rahimnathwani 7y agoDEP 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-black.rst https://github.com/django/deps/blob/master/accepted/0008-bla... https://groups.google.com/forum/#!topic/django-developers/7GZE3fIVVvo https://groups.google.com/forum/#!topic/django-developers/7G...
- di 7y agoSeems 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
- infecto 7y agoI 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 7y agoThat'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 7y agoIt'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 7y agoTechnically, 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.
- timothycrosley 7y agoBlack 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.
- alexhutcheson 7y agoFeature 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 7y agoSounds 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 7y agoMost 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.
- jhrmnn 7y ago
- andrewljohnson 7y agoWe 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 7y agoBecause 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 7y agoI 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 7y agoYour 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
- gubbrora 7y agoI 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 7y agoDoesn’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.
- PhilipTrauner 7y agoSince 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!
- yingw787 7y agoI 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.
- davidjhall 7y agoWhy 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 7y agoThose look the same to me.
- pritambaral 7y agoPerhaps your parent failed to add double-newlines and HN's formatting ate their newlines, but notice the extra word "lines" at the end.
- davidjhall 7y agoBecause I'm dumb. :-( First line was a single line The next line was multiple lines as per https://news.ycombinator.com/item?id=19944722 https://news.ycombinator.com/item?id=19944722 above.
- davidjhall 7y agomeant to be: printable_chars = { 33, 34, 35 [...and another few hundred ] to printable_chars = { 33, 34, 35 [...and another few hundred lines ] }
- danbrooks 7y agoBlack is my favorite auto formatter. I use it for python scripts and blackcellmagic for jupyter notebooks.
- mychael 7y agoHaving 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 7y agoHaving 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 7y agoYay! 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?
- jsmeaton 7y agoDisagree. It’s extremely close to the Django style guide for example. And it’s very close to the style guide we adopted at $work$.
- pletnes 7y agoHow 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 7y agoAt 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.
- jsmeaton 7y agoWe use pre-commit https://github.com/pre-commit/pre-commit https://github.com/pre-commit/pre-commit locally so everyone has the same thing configured. Then we execute pre-commit from the CLI in our CI so that it’s the same as local.
- john-radio 7y agoI 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 7y agoSeems 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 7y agoIf 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.html https://black.readthedocs.io/en/stable/editor_integration.ht...
- schemathings 7y agoFWIW gg=G formats in vim (whole doc), with lots of variations available .. more examples: https://stackoverflow.com/questions/506075/how-do-i-fix-the-indentation-of-an-entire-file-in-vi https://stackoverflow.com/questions/506075/how-do-i-fix-the-...
- neuronexmachina 7y agoMy 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
- laktak 7y agoMore languages should have this. Does anybody know of a c# autoformatter that works on Linux?
- hawaiian 7y ago>uncompromising But does it have an #ignoreformatter directive?
- syockit 7y agoYes. # fmt: off unformatted code goes here # fmt: on
- jdoliner 7y agoI sincerely hope that adding this to your project is referred to as "taking the Black." Too good an opportunity to miss.
- dethos 7y agoBlack 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.
- quietbritishjim 7y agoAuto 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 7y agoBlack does add brackets in some situations.
- quietbritishjim 7y agoFrankly, 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.
- jhayward 7y agoMy quick review of some changes Black made in the mercurial code base pointed out this same kind of thing in comprehensions, and a similar problem in the expressions of if statement. I think the newline-after-bracket behavior looks like some brain damage based on how it likes lists formatted. The complaint I have on if clauses is that it doesn't break at logical operators, but rather at an open-paren, which just ruins the readability of compound expressions.
- haraball 7y agoBeside 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,
- dewiz 7y agoI 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 :-)
- josh2600 7y agoMy friend (who played keyboard in my jazz quartet until he moved to Europe) is the author of this! It's super cool. Hi Lukasz!!
- tlrobinson 7y agoAutomatic 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.
- yellowapple 7y agoPlayed 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 7y agoBecause 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.
- georgyo 7y agoThe line length thing is what I hate the most about black. It's way too religious. For strings, it will format it like he formatted the array, and adding a word will reflow the entire block of text.
- anoncake 7y agoSometimes, optimizing for the smallest diff is clearly not worth it. For example: months = ["January", "February", "March", ...] A human can make a smart decision, an autoformatter can't.
- davidjhall 7y agoPlus, finding the change isn't that hard, compared to munging your 1 or 2 line assignment into 30. A good diff will tell you: 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 ] vs. >> foo = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ] Better ones will underline the offending characters.
- zahreeley 7y agoWhy such name? Can I say it loud in office premises?
- AceJohnny2 7y agoBikeshedding: The Thread.
- jordic 7y agoperhaps 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 7y agoThis exists now :)
- jaimebuelta 7y agoThere 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)