Upgrade to Pro — share decks privately, control downloads, hide ads and more …

auto code formatting with Black

auto code formatting with Black

I gave this lecture at the “Django User Group Berlin” meetup as a contribution of my company which hosted the event.

Avatar for Gregor Gärtner

Gregor Gärtner

February 19, 2019

Other Decks in Technology

Transcript

  1. “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.”
  2. Why auto formatting? primary benefits – focus on the code,

    
 not on its form – consistent code style 
 across different projects – smallest diffs possible secondary benefits – shorter style guides – more effective code reviews – faster onboarding – save time and mental energy – be more productive
  3. Why Black? alternatives – autopep8
 focus on PEP compliance –

    YAPF
 most flexible Black – uncompromising and radical – very few configuration options
  4. “Black reformats entire files in place. It is not configurable.

    It doesn't take previous formatting into account.”
  5. How to get it up and running – works with

    Python 3.6 and higher – can format code of any Python version from 2.7 upwards pip install black black <source-file>
  6. The Black style – “whatever makes pycodestyle happy”
 (strict subset

    of PEP 8) – line wrapping:
 1. fit in one line
 2. fit contents of enclosing brackets in one line
 3. decompose using the same rule (= one line per item) – double quotes only (optional) – line breaks before binary operator
  7. What remains untouched – Single empty lines inside functions won’t

    be removed. – Black does not insert empty lines after a module-level comment which immediately precedes a definition.
  8. Emergency exit # fmt: off i_love_squares = [ 1, 2,

    3, 4, 5, 6, 7, 8, 9, ] # fmt: on
  9. Our worries and reservations – Dedicatedly-crafted code passages will be

    disfigured. – We must let go of sensible custom conventions. – We will be subject to someone else’s style preferences, which may also change over time. – Repeated small changes will result in code being formatted back and forth.
  10. Caveats – details of formatting style might change due to

    beta status
 “No drastic stylistic changes are planned, mostly responses to bug reports.” – rare edge cases where Black is not possible to satisfy the rules
  11. Sources and resources Black – repo on GitHub: github.com/ambv/black/ –

    documentation: black.readthedocs.io – playground: black.now.sh automatic code formatting – Kevin Peters: Auto formatters for Python (June 2018)
  12. Jonas und der Wolf GmbH
 Alt-Moabit 104
 10559 Berlin jonasundderwolf.de


    [email protected] +49 (0)30 22 40 99 – 0 Gregor Gärtner
 software developer
 19 February 2019