The uncompromising Python code formatter

Overview

Black Logo

The Uncompromising Code Formatter

Build Status Actions Status Actions Status Documentation Status Coverage Status License: MIT PyPI Downloads conda-forge Code style: black

“Any color you like.”

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.

Blackened code looks the same regardless of the project you're reading. Formatting becomes transparent after a while and you can focus on the content instead.

Black makes code review faster by producing the smallest diffs possible.

Try it out now using the Black Playground. Watch the PyCon 2019 talk to learn more.


Contents: Installation and usage | Code style | Pragmatism | pyproject.toml | Editor integration | blackd | black-primer | Version control integration | GitHub Actions | Ignoring unmodified files | Used by | Testimonials | Show your style | Contributing | Change log | Authors


Installation and usage

Installation

Black can be installed by running pip install black. It requires Python 3.6.0+ to run but you can reformat Python 2 code with it, too.

Install from GitHub

If you can't wait for the latest hotness and want to install from GitHub, use:

pip install git+git://github.com/psf/black

Usage

To get started right away with sensible defaults:

black {source_file_or_directory}

You can run Black as a package if running it as a script doesn't work:

python -m black {source_file_or_directory}

Command line options

Black doesn't provide many options. You can list them by running black --help:

Usage: black [OPTIONS] [SRC]...

  The uncompromising code formatter.

Options:
  -c, --code TEXT                 Format the code passed in as a string.
  -l, --line-length INTEGER       How many characters per line to allow.
                                  [default: 88]

  -t, --target-version [py27|py33|py34|py35|py36|py37|py38|py39]
                                  Python versions that should be supported by
                                  Black's output. [default: per-file auto-
                                  detection]

  --pyi                           Format all input files like typing stubs
                                  regardless of file extension (useful when
                                  piping source on standard input).

  -S, --skip-string-normalization
                                  Don't normalize string quotes or prefixes.
  -C, --skip-magic-trailing-comma
                                  Don't use trailing commas as a reason to
                                  split lines.

  --check                         Don't write the files back, just return the
                                  status.  Return code 0 means nothing would
                                  change.  Return code 1 means some files
                                  would be reformatted. Return code 123 means
                                  there was an internal error.

  --diff                          Don't write the files back, just output a
                                  diff for each file on stdout.

  --color / --no-color            Show colored diff. Only applies when
                                  `--diff` is given.

  --fast / --safe                 If --fast given, skip temporary sanity
                                  checks. [default: --safe]

  --include TEXT                  A regular expression that matches files and
                                  directories that should be included on
                                  recursive searches.  An empty value means
                                  all files are included regardless of the
                                  name.  Use forward slashes for directories
                                  on all platforms (Windows, too).  Exclusions
                                  are calculated first, inclusions later.
                                  [default: \.pyi?$]

  --exclude TEXT                  A regular expression that matches files and
                                  directories that should be excluded on
                                  recursive searches.  An empty value means no
                                  paths are excluded. Use forward slashes for
                                  directories on all platforms (Windows, too).
                                  Exclusions are calculated first, inclusions
                                  later.  [default: /(\.direnv|\.eggs|\.git|\.
                                  hg|\.mypy_cache|\.nox|\.tox|\.venv|\.svn|_bu
                                  ild|buck-out|build|dist)/]

  --force-exclude TEXT            Like --exclude, but files and directories
                                  matching this regex will be excluded even
                                  when they are passed explicitly as
                                  arguments.

  --stdin-filename TEXT           The name of the file when passing it through
                                  stdin. Useful to make sure Black will
                                  respect --force-exclude option on some
                                  editors that rely on using stdin.

  -q, --quiet                     Don't emit non-error messages to stderr.
                                  Errors are still emitted; silence those with
                                  2>/dev/null.

  -v, --verbose                   Also emit messages to stderr about files
                                  that were not changed or were ignored due to
                                  --exclude=.

  --version                       Show the version and exit.
  --config FILE                   Read configuration from FILE path.
  -h, --help                      Show this message and exit.

Black is a well-behaved Unix-style command-line tool:

  • it does nothing if no sources are passed to it;
  • it will read from standard input and write to standard output if - is used as the filename;
  • it only outputs messages to users on standard error;
  • exits with code 0 unless an internal error occurred (or --check was used).

Using Black with other tools

While Black enforces formatting that conforms to PEP 8, other tools may raise warnings about Black's changes or will overwrite Black's changes. A good example of this is isort. Since Black is barely configurable, these tools should be configured to neither warn about nor overwrite Black's changes.

Actual details on Black compatible configurations for various tools can be found in compatible_configs.

Migrating your code style without ruining git blame

A long-standing argument against moving to automated code formatters like Black is that the migration will clutter up the output of git blame. This was a valid argument, but since Git version 2.23, Git natively supports ignoring revisions in blame with the --ignore-rev option. You can also pass a file listing the revisions to ignore using the --ignore-revs-file option. The changes made by the revision will be ignored when assigning blame. Lines modified by an ignored revision will be blamed on the previous revision that modified those lines.

So when migrating your project's code style to Black, reformat everything and commit the changes (preferably in one massive commit). Then put the full 40 characters commit identifier(s) into a file.

# Migrate code style to Black
5b4ab991dede475d393e9d69ec388fd6bd949699

Afterwards, you can pass that file to git blame and see clean and meaningful blame information.

$ git blame important.py --ignore-revs-file .git-blame-ignore-revs
7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 1) def very_important_function(text, file):
abdfd8b0 (Alice Doe  2019-09-23 11:39:32 -0400 2)     text = text.lstrip()
7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 3)     with open(file, "r+") as f:
7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 4)         f.write(formatted)

You can even configure git to automatically ignore revisions listed in a file on every call to git blame.

$ git config blame.ignoreRevsFile .git-blame-ignore-revs

The one caveat is that GitHub and GitLab do not yet support ignoring revisions using their native UI of blame. So blame information will be cluttered with a reformatting commit on those platforms. (If you'd like this feature, there's an open issue for GitLab and please let GitHub know!)

NOTE: This is a beta product

Black is already successfully used by many projects, small and big. It also sports a decent test suite. However, it is still very new. Things will probably be wonky for a while. This is made explicit by the "Beta" trove classifier, as well as by the "b" in the version number. What this means for you is that until the formatter becomes stable, you should expect some formatting to change in the future. That being said, no drastic stylistic changes are planned, mostly responses to bug reports.

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.

The Black code style

Black is a PEP 8 compliant opinionated formatter. Black reformats entire files in place. It is not configurable. It doesn't take previous formatting into account. Your main option of configuring Black is that it doesn't reformat blocks that start with # fmt: off and end with # fmt: on. # fmt: on/off have to be on the same level of indentation. To learn more about Black's opinions, to go the_black_code_style.

Please refer to this document before submitting an issue. What seems like a bug might be intended behaviour.

Pragmatism

Early versions of Black used to be absolutist in some respects. They took after its initial author. This was fine at the time as it made the implementation simpler and there were not many users anyway. Not many edge cases were reported. As a mature tool, Black does make some exceptions to rules it otherwise holds. This section of the_black_code_style describes what those exceptions are and why this is the case.

Please refer to this document before submitting an issue just like with the document above. What seems like a bug might be intended behaviour.

pyproject.toml

Black is able to read project-specific default values for its command line options from a pyproject.toml file. This is especially useful for specifying custom --include and --exclude patterns for your project.

Pro-tip: If you're asking yourself "Do I need to configure anything?" the answer is "No". Black is all about sensible defaults.

What on Earth is a pyproject.toml file?

PEP 518 defines pyproject.toml as a configuration file to store build system requirements for Python projects. With the help of tools like Poetry or Flit it can fully replace the need for setup.py and setup.cfg files.

Where Black looks for the file

By default Black looks for pyproject.toml starting from the common base directory of all files and directories passed on the command line. If it's not there, it looks in parent directories. It stops looking when it finds the file, or a .git directory, or a .hg directory, or the root of the file system, whichever comes first.

If you're formatting standard input, Black will look for configuration starting from the current working directory.

You can also explicitly specify the path to a particular file that you want with --config. In this situation Black will not look for any other file.

If you're running with --verbose, you will see a blue message if a file was found and used.

Please note blackd will not use pyproject.toml configuration.

Configuration format

As the file extension suggests, pyproject.toml is a TOML file. It contains separate sections for different tools. Black is using the [tool.black] section. The option keys are the same as long names of options on the command line.

Note that you have to use single-quoted strings in TOML for regular expressions. It's the equivalent of r-strings in Python. Multiline strings are treated as verbose regular expressions by Black. Use [ ] to denote a significant space character.

Example pyproject.toml
[tool.black]
line-length = 88
target-version = ['py37']
include = '\.pyi?$'
exclude = '''
# A regex preceded with ^/ will apply only to files and directories
# in the root of the project.
^/(
  (
      \.eggs         # exclude a few common directories in the
    | \.git          # root of the project
    | \.hg
    | \.mypy_cache
    | \.tox
    | \.venv
    | _build
    | buck-out
    | build
    | dist
  )/
  | foo.py           # also separately exclude a file named foo.py in
                     # the root of the project
)
'''

Lookup hierarchy

Command-line options have defaults that you can see in --help. A pyproject.toml can override those defaults. Finally, options provided by the user on the command line override both.

Black will only ever use one pyproject.toml file during an entire run. It doesn't look for multiple files, and doesn't compose configuration from different levels of the file hierarchy.

Editor integration

Black can be integrated into many editors with plugins. They let you run Black on your code with the ease of doing it in your editor. To get started using Black in your editor of choice, please see editor_integration.

Patches are welcome for editors without an editor integration or plugin! More information can be found in editor_integration.

blackd

blackd is a small HTTP server that exposes Black's functionality over a simple protocol. The main benefit of using it is to avoid paying the cost of starting up a new Black process every time you want to blacken a file. Please refer to blackd to get the ball rolling.

black-primer

black-primer is a tool built for CI (and humans) to have Black --check a number of (configured in primer.json) Git accessible projects in parallel. black_primer has more information regarding its usage and configuration.

(A PR adding Mercurial support will be accepted.)

Version control integration

Use pre-commit. Once you have it installed, add this to the .pre-commit-config.yaml in your repository:

repos:
  - repo: https://github.com/psf/black
    rev: 20.8b1 # Replace by any tag/version: https://github.com/psf/black/tags
    hooks:
      - id: black
        language_version: python3 # Should be a command that runs python3.6+

Then run pre-commit install and you're ready to go.

Avoid using args in the hook. Instead, store necessary configuration in pyproject.toml so that editors and command-line usage of Black all behave consistently for your project. See Black's own pyproject.toml for an example.

If you're already using Python 3.7, switch the language_version accordingly. Finally, stable is a branch that tracks the latest release on PyPI. If you'd rather run on master, this is also an option.

GitHub Actions

Create a file named .github/workflows/black.yml inside your repository with:

name: Lint

on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/[email protected]
      - uses: actions/[email protected]
      - uses: psf/[email protected]
        with:
          black_args: ". --check"

Inputs

black_args

optional: Black input arguments. Defaults to . --check --diff.

Ignoring unmodified files

Black remembers files it has already formatted, unless the --diff flag is used or code is passed via standard input. This information is stored per-user. The exact location of the file depends on the Black version and the system on which Black is run. The file is non-portable. The standard location on common operating systems is:

  • Windows: C:\\Users\<username>\AppData\Local\black\black\Cache\<version>\cache.<line-length>.<file-mode>.pickle
  • macOS: /Users/<username>/Library/Caches/black/<version>/cache.<line-length>.<file-mode>.pickle
  • Linux: /home/<username>/.cache/black/<version>/cache.<line-length>.<file-mode>.pickle

file-mode is an int flag that determines whether the file was formatted as 3.6+ only, as .pyi, and whether string normalization was omitted.

To override the location of these files on macOS or Linux, set the environment variable XDG_CACHE_HOME to your preferred location. For example, if you want to put the cache in the directory you're running Black from, set XDG_CACHE_HOME=.cache. Black will then write the above files to .cache/black/<version>/.

Used by

The following notable open-source projects trust Black with enforcing a consistent code style: pytest, tox, Pyramid, Django Channels, Hypothesis, attrs, SQLAlchemy, Poetry, PyPA applications (Warehouse, Bandersnatch, Pipenv, virtualenv), pandas, Pillow, every Datadog Agent Integration, Home Assistant.

The following organizations use Black: Facebook, Dropbox, Mozilla, Quora.

Are we missing anyone? Let us know.

Testimonials

Dusty Phillips, writer:

Black is opinionated so you don't have to be.

Hynek Schlawack, creator of attrs, core developer of Twisted and CPython:

An auto-formatter that doesn't suck is all I want for Xmas!

Carl Meyer, Django core developer:

At least the name is good.

Kenneth Reitz, creator of requests and pipenv:

This vastly improves the formatting of our code. Thanks a ton!

Show your style

Use the badge in your project's README.md:

[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

Using the badge in README.rst:

.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
    :target: https://github.com/psf/black

Looks like this: Code style: black

License

MIT

Contributing to Black

In terms of inspiration, Black is about as configurable as gofmt. This is deliberate.

Bug reports and fixes are always welcome! However, before you suggest a new feature or configuration knob, ask yourself why you want it. If it enables better integration with some workflow, fixes an inconsistency, speeds things up, and so on - go for it! On the other hand, if your answer is "because I don't like a particular formatting" then you're not ready to embrace Black yet. Such changes are unlikely to get accepted. You can still try but prepare to be disappointed.

More details can be found in CONTRIBUTING.

Change log

The log's become rather long. It moved to its own file.

See CHANGES.

Authors

Glued together by Łukasz Langa.

Maintained with Carol Willing, Carl Meyer, Jelle Zijlstra, Mika Naylor, Zsolt Dollenstein, and Cooper Lees.

Multiple contributions by:

Issues
  • Non-prerelease black release

    Non-prerelease black release

    It looks like Black is stable enough at the moment to release it as stable to PyPI. There are plenty of tools and integrations already which rely on black package and the fact that it is still in prerelease state sometime causes inconveniences, i.e. using it with pipenv forces allow_prereleases flag to be set to true.

    C: installation / packaging C: maintenance 
    opened by lig 113
  • "INTERNAL ERROR: Black produced different code on the second pass of the formatter"

    • Version: 20.8b0
    • OS and Python version: all

    This is a rare problem that we're currently investigating. The most common case of it has to do with a combination of magic trailing commas and optional parentheses. Long story short, there's this behavior:

    • Black now treats all pre-existing trailing magic commas found in bracket pairs as signal to explode that bracket pair (e.g. to format it "one element per line");
    • in other places Black inserts trailing commas itself after reformatting a long expression or statement;
    • then on another run, Black finds those trailing commas and treats them as pre-existing trailing commas that signal that the given bracket pair should be exploded.

    The expected behavior is that there should be no difference between the first formatting and the second formatting. In practice Black sometimes chooses for or against optional parentheses differently depending on whether the line should be exploded or not. This is what needs fixing.

    Workaround

    We're working on fixing this, until then, format the file twice with --fast, it will keep its formatting moving forward.

    Call To Action

    If you find a case of this, please attach the generated log here so we can investigate. We've already added three identifying examples of this as expected failures to https://github.com/psf/black/pull/1627/commits/25206d8cc6e98143f0b10bcbe9e8b41b8b543abe.

    Finally, if you're interested in debugging this yourself, look for should_explode in if statements in the Black codebase. Those are the decisions that lead to unstable formatting.

    T: bug C: unstable formatting F: parentheses F: trailing comma 
    opened by ambv 80
  • Single quotes option

    Single quotes option

    Hi! Although Black now prefers doubles, can we have an option to keep single quotes? Forcing double quotes would make this great project unusable for many users who picked the rule of using single quotes.

    Operating system: MacOS Python version: 3.6 Black version: 18.4a0 Does also happen on master: yes

    T: design 
    opened by bofm 72
  • Black should have an opinion about doc strings

    Black should have an opinion about doc strings

    Operating system: Ubuntu 16.04 Python version: 3.6.1 Black version: master Does also happen on master: yes

    Hi,

    currently Black doesn't seem to have an opinion about doc strings or rather where the quotes should go.

    Black claims for this file for example that it is already formatted:

    def test():
        """This is one possibility.
    
        Very important stuff here.
        """
    
    
    def test2():
        """This is another one possibility.
    
        Very important stuff here."""
    
    
    def test3():
        """
        This is another one possibility.
    
        Very important stuff here.
        """
    
    
    def test4():
        """
        What about this?
        """
    
    
    def test5():
        """What about this?
    
        Some people also like to have an empty line at the end of the doc string.
    
        """
    

    The tool pydocstyle (in the spirit of PEP-0257) at least complains that the closing quotes should go on a separate line and if the docstring fits one line it should only span one line.

    It would be nice if that could be incorporated in Black as well.

    Thanks for the great work!

    Lukas.

    T: enhancement help wanted good first issue T: design 
    opened by Lukas0907 68
  • tweak collection literals to explode with trailing comma

    tweak collection literals to explode with trailing comma

    This is a change I discussed with @ambv at PyCon - the commit sequence should make things clear. I didn't go to the effort of fixing up existing tests (they'll fail a lot right now), but I can if this looks like a valid approach. This is somewhere between "proof of concept" and something I'd feel happy about, but I wanted feedback on how I'm tackling this early in development since I'm very much noideadog on this code.

    opened by durin42 65
  • Finish

    Finish "magic trailing comma" handling

    #826 introduced the concept of a magic trailing comma: if you, the programmer, explicitly put a trailing comma in a collection, it signals to Black that you want a given collection exploded into multiple lines, always. While this flies a bit in the way of "doesn't look at pre-existing formatting" and "non-configurability", it is extremely pragmatic and consistent with "make diffs as small as possible".

    However, there's issues with it so far. It doesn't yet work on nested collections. Worse yet, in those cases it leaves trailing commas behind when a collection ends up compressed into one line. We need to fix those edge cases to make it generally dependable.

    T: bug 
    opened by ambv 54
  • Black violates pep8 recommendation with long argument list

    Black violates pep8 recommendation with long argument list

    Currently, black reformats long routine names as follow

    # in:
    
    def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
        """Applies `variables` to the `template` and writes to `file`."""
        with open(file, 'w') as f:
            ...
    
    # out:
    
    def very_important_function(
        template: str,
        *variables,
        file: os.PathLike,
        engine: str,
        header: bool = True,
        debug: bool = False,
    ):
        """Applies `variables` to the `template` and writes to `file`."""
        with open(file, "w") as f:
    

    Desired style

    The current style done by black violates pep8 recommendation

    # Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest.
    def long_function_name(
            var_one, var_two, var_three,
            var_four):
        print(var_one)
    

    The logic and motivation behind pep8 formatting, and against black, is that one wants to keep the indentation of the function definition continuation at a different level compared to the logic block. Otherwise, it's harder to differentiate what's one and what's the other, despite the indented frowny face.

    In fact, flake8 reports a pep8 violation for a case such as this

        if path.suffix in (
            '.js', '.json'
            ):
            proto = Protocol.json
    
    x.py:20:5: E125 continuation line with same indent as next logical line
    

    Black current formatting would be equivalent to this

        if path.suffix in (
            '.js', '.json'
        ):
            proto = Protocol.json
    

    Which we can probably all agree is a bad idea.

    Additional context from python-ideas mailing list

    T: design 
    opened by stefanoborini 54
  • Black does not honor exclude regex when files explicitly listed on the command line

    Black does not honor exclude regex when files explicitly listed on the command line

    Operating system: OSX Python version: 3.6.2 Black version: black, version 18.6b4

    The problem: certain directories in our repo contain generated python code that we don't want black to change. We've configure our repo to run black via pre-commit. Pre-commit invokes black with a list of changed files on the command line, and black's exclude regex does not work against those files and paths.

    i.e.

    black --exclude "/migrations/" content/migrations/0049_publicationstore_is_test.py
    reformatted content/migrations/0049_publicationstore_is_test.py
    All done! ✨ 🍰 ✨
    1 file reformatted.
    

    This makes us sad, since we've carefully put exclusion regexes into our pyproject.toml and black doesn't honor them when pre-commit calls it. Instead, we're having to workaround by configuring pre-commit to skip that path:

    repos:
    -   repo: https://github.com/ambv/black
        rev: stable
        hooks:
        - id: black
          language_version: python3.6
          exclude: migrations
    

    The behavior we'd like to see is that black's exclude regex would apply even when full file paths are listed on the commandline. I'd be happy to try for a PR if this seems like desirable behavior to anyone else...

    opened by adamehirsch 48
  • Fluent interfaces

    Fluent interfaces

    Operating system: Mac OS Python version: 3.6.4 Black version: 18.3a3 Does also happen on master: yes


    Black removes trailing backlashes, which can be used, for instance with yapf, to signal "don't join these line".

    This is problematic, for instance, if one uses the "fluent interface" idiom, which can lead to long chains of attribute accesses in a given expression.

    Here's an example:

    -        return sa.sql \
    -            .select([sa.sql.func.count(membership.c.user_id)]) \
    -            .where(membership.c.group_id == cls.id) \
    -            .group_by(membership.c.group_id) \
    -            .label('members_count')
    +        return sa.sql.select([sa.sql.func.count(membership.c.user_id)]).where(
    +            membership.c.group_id == cls.id
    +        ).group_by(
    +            membership.c.group_id
    +        ).label(
    +            'members_count'
    +        )
    

    The easiest solution would be to keep the line break in the presence of a backslash.

    T: enhancement help wanted 
    opened by sfermigier 43
  • Offer option other than pyproject.toml for config

    Offer option other than pyproject.toml for config

    https://github.com/pypa/pip/issues/6163 https://github.com/pypa/setuptools/issues/1642

    It seems that pyproject.toml is a trigger for enabling PEP 517 isolated builds. This seems a not good thing to tie to configuration of black. It broke pyinstaller and others with the pip-19.0 release.

    T: enhancement 
    opened by altendky 41
  • Incompatible with click 8.1.0 (ImportError: cannot import name '_unicodefun' from 'click')

    Incompatible with click 8.1.0 (ImportError: cannot import name '_unicodefun' from 'click')

    Please use Black 22.3.0 which was just released to fix this issue or pin Click to 8.0.0, 8.0.1, 8.0.2, 8.0.3, or 8.0.4.

    ~ @ichard26 at March 28 3:15 PM EST


    So hey y'all, CI is broken eh?

    Anyway, we are aware the most recent release of Click, 8.1.0, is breaking Black. This is because Black imports an internal module so Python 3.6 users with misconfigured LANG continues to work mostly properly. The code that patches click was supposed to be resilient to the module disappearing but the code was catching the wrong exception.

    To unbreak your CI, please pin Click to 8.0.0, 8.0.1, 8.0.2, 8.0.3, or 8.0.4. We are working on a more longterm fix (probably fixing the patching code or getting rid of it entirely) and will try to get a release out soon.

    ~ @ichard26 at March 28 2:29 PM EST


    Describe the bug

    The Github Action step:

    - name: Run black
      uses: psf/[email protected]
      with:
         options: "--check --diff"
          version: "22.1.0"
    

    fails with the following trackeback:

    Traceback (most recent call last):
      File "/home/runner/work/_actions/psf/black/stable/.black-env/bin/black", line 8, in <module>
        sys.exit(patched_main())
      File "src/black/__init__.py", line 1423, in patched_main
      File "src/black/__init__.py", line 1[40](https://github.com/stumpylog/paperless-ngx/runs/5724998040?check_suite_focus=true#step:7:40)9, in patch_click
    ImportError: cannot import name '_unicodefun' from 'click' (/home/runner/work/_actions/psf/black/stable/.black-env/lib/python3.8/site-packages/click/__init__.py)
    

    To Reproduce

    Run the black action on a Github runner, configured as above.

    Expected behavior

    The action should only fail if files are not formatted.

    Environment

    OS: runs-on: ubuntu-20.04 Version: 22.1.0 Action: @stable Python version: 3.8 I believe

    Additional context

    T: bug C: installation / packaging 
    opened by stumpylog 40
  • Don't insert extra blank lines at the start of an indent

    Don't insert extra blank lines at the start of an indent

    Describe the style change

    If a function/class is defined at the start of a non-scoping indent (e.g. if, for) a blank line is inserted before the function. I would like this removed, since:

    • If an indent is scoping (e.g. def, class) no blank line is inserted and I would prefer if style was consistent.
    • I believe this is redundant since the indent already separates the function/class definition well enough.

    Examples in the current Black style

    # No blank lines
    def f():
        def g():
            pass
    
    
    class A:
        def g():
            pass
    
    
    # Blank lines
    for _ in range(10):
    
        def g():
            pass
    
    
    if True:
    
        def g():
            pass
    

    Desired style

    # No blank lines
    def f():
        def g():
            pass
    
    
    class A:
        def g():
            pass
    
    
    # Also, no blank lines
    for _ in range(10):
        def g():
            pass
    
    
    if True:
        def g():
            pass
    

    Additional context

    The issue came up when my team was developing a tool to remove blank lines at the start of indents, would be cool if black autocorrected that as well.

    T: design F: empty lines 
    opened by Rizhiy 0
  • Proposal: Shades of Black

    Proposal: Shades of Black

    We often get proposals for formatting changes that could be useful, but that change the AST or are otherwise unsafe. Examples include:

    • Import sorting (#333)
    • Formatting stringified annotations (#3067)
    • Dropping useless f-strings (#3081)
    • Aspects of docstring formatting (#144, #2150)
    • not (x in y) (#212)

    Many of these proposals make sense as an extension of Black's mission to create a single, consistent style for Python code, but users have legitimate concerns about the safety of such changes.

    Relatedly, there are some tools that wrap Black together with other formatters:

    • https://github.com/Zac-HD/shed (black+isort+pyupgrade+autoflake+blacken-docs)
    • https://github.com/omnilib/ufmt (black+usort)

    However, these tools have not reached Black's level of popularity. Creating this logic in Black itself would make it more discoverable for users.

    I observed that several of the existing formatting options can be described as "either leave it alone, or let Black make its decision": --skip-string-normalization, --skip-magic-trailing-comma. That's a useful principle to follow: formatting options shouldn't be about using one style or another, only about whether to handle some aspect of formatting at all.

    Proposal

    So here's the proposal: There is only one Black code style, but you get a choice how far you commit to it. We'd introduce a system of shades, aspects of formatting that can be individually turned on or off depending on what is safe on your codebase. Initial shades could include:

    • String normalization: on by default; if off, string quotes are left alone.
    • Docstrings: on by default; if off, docstrings are not changed at all.
    • Misc AST unsafe: on by default; if off (and other AST-changing options are off), we guarantee full AST safety. I believe this would currently only affect del parentheses, but we could make a few other things go into this group (#3081, #212). These would be things that change the AST, but in minor ways that we're confident don't change the meaning of the program.
    • Magic trailing comma: off by default; if on, we ignore pre-existing magic trailing commas.

    In the future, we could add additional shades for import sorting, annotation formatting, and other automatic improvements to Python code.

    We could add shortcut options for enabling all shades, like black --all-the-way for enabling everything, and black --super-safe for disabling all AST-unsafe options for the paranoid among us. (Names could be improved.)

    These new shades would be orthogonal to --preview style and the stability policy: any new shades would be enabled only in --preview mode until the new year starts.

    Alternatives

    • Do nothing. The proposal adds significant complexity to Black, and we've billed ourselves as a simple, no-configuration tool. I have a lot of sympathy for this position. But if we don't do it, people will build other tools for additional formatting, creating a more fragmented ecosystem that's harder for users to navigate. Black has a chance to provide a much simpler solution to users.
    T: enhancement T: design S: needs discussion 
    opened by JelleZijlstra 1
  • Black not line wrapping tuples with long strings

    Black not line wrapping tuples with long strings

    Describe the bug

    Black should put parentheses and wrap this tuple over multiple lines:

    def asdf():
        for item in items:
            yield item, "this is a really long string describing item. you'd expect black to put parentheses around the tuple."
    

    To Reproduce

    https://black.vercel.app/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ADxAK5dAD2IimZxl1N_WlbvK5V8JNI77iY4W6dVOfyLjNFiaj70Bl3KDmvzUGa515Sxf8PkVW3bG3ae8JNP373LwFgPbvHVIPAE-XJtpbaXte5disESbEB-JtiPSKxPO0dJ9-wDbroDvrdVhhvDMK9VMixYumgWDHNgwfYwkhJSr-_yuGqWhJUZw_mE17rS3JC6V278eYev_bAfCNjaRI2eyTB4Xyv47363qrV197jUTm0eAAAAAOLHMH_IDVfUAAHKAfIBAACkdOtjscRn-wIAAAAABFla

    T: bug F: linetoolong 
    opened by hauntsaninja 1
  • Show trailing space in diff in explicit way

    Show trailing space in diff in explicit way

    Hi, I have a project with precommit hook that calls [black --check --diff] and fails commit on non-empty diff. Egor (collegue of mine) suddenly added space after last character in line but diff looks confusing:

    -) 
    +)
    

    I could see the source by checkout his branch and running black over it but this is a long way. Could black show trailing spaces in some explicit way? It will be appreciated even by specifying some CLI option. Thank you.

    T: enhancement 
    opened by abcdenis 1
  • Introduce Pants to the repo, as a proof of concept.

    Introduce Pants to the repo, as a proof of concept.

    Description

    This change introduces the Pants build system to the Black repo, on an experimental basis.

    It does not change any of the existing build mechanisms for running tests, formatting, linting, typechecking, building distributions etc. Developers in this repo can remain unaware of Pants if they choose. Others may be interested in playing around with it.

    For context: While chatting with @ambv at PyCon 2022 he expressed interest in seeing what using Pants in the Black repo would look like. This change is a proof-of-concept as a result of that conversation.

    Notes to reviewers:

    • This PR consists of several commits that, while not fully independent, are useful to review individually. Each commit's message describes in more detail what it contains.
    • My apologies for the size of the diff (8298 lines!). However it's not what it seems:
      • 7232 lines are generated lockfiles.
      • 418 lines are standard Pants runner scripts.
      • 253 lines are "BUILD file" boilerplate and metadata, much of it also generated.
      • 244 lines are the new docs/contributing/pants.md documentation file, worth reading for more detail.
      • 151 lines are miscellaneous changes, and these are worth the greatest line-by-line scrutiny.
      • The commit messages will help distinguish which is which.
    • Thanks for taking the time to review this. I'm happy to answer any questions, and the Pants community is a good place for any questions or conversation outside the scope of this PR, if needed.
    What is Pants, and why might you want to use it?

    Pants is a modern build system with a strong focus on Python. It installs, configures and orchestrates the underlying tools, such as pytest, flake8, setuptools, mypy, and, of course, Black itself. Pants provides a uniform CLI interface for build actions. It aims to make builds repeatable, stable, fast and secure. It achieves these goals via features such as: dependency inference, fine-grained invalidation, caching, concurrency, lockfiles, hermetic execution and more.

    Checklist - did you ...

    • [ ] Add a CHANGELOG entry if necessary?
    • [x] Add / update tests if necessary?
    • [x] Add new / update outdated documentation?

    My understanding is that this change doesn't require a CHANGELOG entry, since it doesn't modify Black itself in any way, and is not user-visible. But please let me know if I am wrong about this!

    opened by benjyw 1
  • Doctests formatting in Docstrings

    Doctests formatting in Docstrings

    Is your feature request related to a problem? Please describe.

    Black currently does not format Doctests in Docstrings. This issues was reported in https://github.com/psf/black/issues/745 which was superseeded by https://github.com/psf/black/issues/144.

    As the latter was closed though, nothing was done about the Doctests.

    Describe the solution you'd like

    I would be keen for black to format Doctest.

    For example, given the following Python Doctests code:

        >>> XYZ = np.array([0.20654008, 0.12197225, 0.05136952])
        >>> LMS_to_LMS_p_callable = lambda x: x ** 0.43
        >>> matrix_XYZ_to_LMS = np.array(
        ...     [[0.4002, 0.7075, -0.0807],
        ...      [-0.2280, 1.1500, 0.0612],
        ...      [0.0000, 0.0000, 0.9184]])
        >>> matrix_LMS_p_to_Iab = np.array(
        ...     [[0.4000, 0.4000, 0.2000],
        ...      [4.4550, -4.8510, 0.3960],
        ...      [0.8056, 0.3572, -1.1628]])
        >>> XYZ_to_Iab(
        ...     XYZ, LMS_to_LMS_p_callable, matrix_XYZ_to_LMS, matrix_LMS_p_to_Iab)
    

    black could produce the following output:

        >>> XYZ = np.array([0.20654008, 0.12197225, 0.05136952])
        >>> LMS_to_LMS_p_callable = lambda x: x**0.43
        >>> matrix_XYZ_to_LMS = np.array(
        ...     [
        ...         [0.4002, 0.7075, -0.0807],
        ...         [-0.2280, 1.1500, 0.0612],
        ...         [0.0000, 0.0000, 0.9184],
        ...     ]
        ... )
        >>> matrix_LMS_p_to_Iab = np.array(
        ...     [
        ...         [0.4000, 0.4000, 0.2000],
        ...         [4.4550, -4.8510, 0.3960],
        ...         [0.8056, 0.3572, -1.1628],
        ...     ]
        ... )
        >>> XYZ_to_Iab(
        ...     XYZ, LMS_to_LMS_p_callable, matrix_XYZ_to_LMS, matrix_LMS_p_to_Iab
        ... )
    

    Describe alternatives you've considered

    I'm manually formatting the code.

    Additional context

    N/A

    T: enhancement F: strings / docstrings 
    opened by KelSolaar 0
Releases(22.3.0)
  • 22.3.0(Mar 28, 2022)

    Preview style

    • Code cell separators #%% are now standardised to # %% (#2919)
    • Remove unnecessary parentheses from except statements (#2939)
    • Remove unnecessary parentheses from tuple unpacking in for loops (#2945)
    • Avoid magic-trailing-comma in single-element subscripts (#2942)

    Configuration

    • Do not format __pypackages__ directories by default (#2836)
    • Add support for specifying stable version with --required-version (#2832).
    • Avoid crashing when the user has no homedir (#2814)
    • Avoid crashing when md5 is not available (#2905)
    • Fix handling of directory junctions on Windows (#2904)

    Documentation

    • Update pylint config documentation (#2931)

    Integrations

    • Move test to disable plugin in Vim/Neovim, which speeds up loading (#2896)

    Output

    • In verbose, mode, log when Black is using user-level config (#2861)

    Packaging

    • Fix Black to work with Click 8.1.0 (#2966)
    • On Python 3.11 and newer, use the standard library's tomllib instead of tomli (#2903)
    • black-primer, the deprecated internal devtool, has been removed and copied to a separate repository (#2924)

    Parser

    • Black can now parse starred expressions in the target of for and async for statements, e.g for item in *items_1, *items_2: pass (#2879).
    Source code(tar.gz)
    Source code(zip)
    black_linux(17.03 MB)
    black_macos(7.26 MB)
    black_windows.exe(7.71 MB)
  • 22.1.0(Jan 29, 2022)

    At long last, Black is no longer a beta product! This is the first non-beta release and the first release covered by our new stability policy.

    Highlights

    • Remove Python 2 support (#2740)
    • Introduce the --preview flag (#2752)

    Style

    • Deprecate --experimental-string-processing and move the functionality under --preview (#2789)
    • For stubs, one blank line between class attributes and methods is now kept if there's at least one pre-existing blank line (#2736)
    • Black now normalizes string prefix order (#2297)
    • Remove spaces around power operators if both operands are simple (#2726)
    • Work around bug that causes unstable formatting in some cases in the presence of the magic trailing comma (#2807)
    • Use parentheses for attribute access on decimal float and int literals (#2799)
    • Don't add whitespace for attribute access on hexadecimal, binary, octal, and complex literals (#2799)
    • Treat blank lines in stubs the same inside top-level if statements (#2820)
    • Fix unstable formatting with semicolons and arithmetic expressions (#2817)
    • Fix unstable formatting around magic trailing comma (#2572)

    Parser

    • Fix mapping cases that contain as-expressions, like case {"key": 1 | 2 as password} (#2686)
    • Fix cases that contain multiple top-level as-expressions, like case 1 as a, 2 as b (#2716)
    • Fix call patterns that contain as-expressions with keyword arguments, like case Foo(bar=baz as quux) (#2749)
    • Tuple unpacking on return and yield constructs now implies 3.8+ (#2700)
    • Unparenthesized tuples on annotated assignments (e.g values: Tuple[int, ...] = 1, 2, 3) now implies 3.8+ (#2708)
    • Fix handling of standalone match() or case() when there is a trailing newline or a comment inside of the parentheses. (#2760)
    • from __future__ import annotations statement now implies Python 3.7+ (#2690)

    Performance

    • Speed-up the new backtracking parser about 4X in general (enabled when --target-version is set to 3.10 and higher). (#2728)
    • Black is now compiled with mypyc for an overall 2x speed-up. 64-bit Windows, MacOS, and Linux (not including musl) are supported. (#1009, #2431)

    Configuration

    • Do not accept bare carriage return line endings in pyproject.toml (#2408)
    • Add configuration option (python-cell-magics) to format cells with custom magics in Jupyter Notebooks (#2744)
    • Allow setting custom cache directory on all platforms with environment variable BLACK_CACHE_DIR (#2739).
    • Enable Python 3.10+ by default, without any extra need to specify --target-version=py310. (#2758)
    • Make passing SRC or --code mandatory and mutually exclusive (#2804)

    Output

    • Improve error message for invalid regular expression (#2678)
    • Improve error message when parsing fails during AST safety check by embedding the underlying SyntaxError (#2693)
    • No longer color diff headers white as it's unreadable in light themed terminals (#2691)
    • Text coloring added in the final statistics (#2712)
    • Verbose mode also now describes how a project root was discovered and which paths will be formatted. (#2526)

    Packaging

    • All upper version bounds on dependencies have been removed (#2718)
    • typing-extensions is no longer a required dependency in Python 3.10+ (#2772)
    • Set click lower bound to 8.0.0 as Black crashes on 7.1.2 (#2791)

    Integrations

    • Update GitHub action to support containerized runs (#2748)

    Documentation

    • Change protocol in pip installation instructions to https:// (#2761)
    • Change HTML theme to Furo primarily for its responsive design and mobile support (#2793)
    • Deprecate the black-primer tool (#2809)
    • Document Python support policy (#2819)

    Full Changelog: https://github.com/psf/black/compare/21.12b0...22.1.0


    Thank you!

    • @isidentical for their continued work on making our Python 3.10 support better than ever (we made them a co-maintainer :tada:)
    • @hauntsaninja for their help improving our stub style
    • @nipunn1313 making Black more stable (which has been a long running battle)
    • .. and all of my fellow co-maintainers who have made working on this project a wonderful ride @JelleZijlstra @cooperlees @felix-hilden @ambv @zsol

    And also congrats to first contributors!

    • @mwtoews made their first contribution in https://github.com/psf/black/pull/2701
    • @gunungpw made their first contribution in https://github.com/psf/black/pull/2733
    • @joshowen made their first contribution in https://github.com/psf/black/pull/2748
    • @Shivansh-007 made their first contribution in https://github.com/psf/black/pull/2526
    • @cbows made their first contribution in https://github.com/psf/black/pull/2761
    • @jlazar17 made their first contribution in https://github.com/psf/black/pull/2765
    • @VanSHOE made their first contribution in https://github.com/psf/black/pull/2712
    • @emfdavid made their first contribution in https://github.com/psf/black/pull/2786
    • @mgmarino made their first contribution in https://github.com/psf/black/pull/2744
    • @RHammond2 made their first contribution in https://github.com/psf/black/pull/2792
    • @percurnicus made their first contribution in https://github.com/psf/black/pull/2739
    • @sobolevn made their first contribution in https://github.com/psf/black/pull/2802
    Source code(tar.gz)
    Source code(zip)
    black_linux(17.03 MB)
    black_macos(7.23 MB)
    black_windows.exe(7.68 MB)
  • 21.12b0(Dec 5, 2021)

    Black

    • Fix determination of f-string expression spans (#2654)
    • Fix bad formatting of error messages about EOF in multi-line statements (#2343)
    • Functions and classes in blocks now have more consistent surrounding spacing (#2472)

    Jupyter Notebook support

    • Cell magics are now only processed if they are known Python cell magics. Earlier, all cell magics were tokenized, leading to possible indentation errors e.g. with %%writefile. (#2630)
    • Fix assignment to environment variables in Jupyter Notebooks (#2642)

    Python 3.10 support

    • Point users to using --target-version py310 if we detect 3.10-only syntax (#2668)
    • Fix match statements with open sequence subjects, like match a, b: or match a, *b: (#2639) (#2659)
    • Fix match/case statements that contain match/case soft keywords multiple times, like match re.match() (#2661)
    • Fix case statements with an inline body (#2665)
    • Fix styling of starred expressions inside match subject (#2667)
    • Fix parser error location on invalid syntax in a match statement (#2649)
    • Fix Python 3.10 support on platforms without ProcessPoolExecutor (#2631)
    • Improve parsing performance on code that uses match under --target-version py310 up to ~50% (#2670)

    Packaging

    • Remove dependency on regex (#2644) (#2663)

    Thank you!

    • @isidentical for the polishing up 3.10 syntax support (which they contributed in the first place!)
    • @MarcoGorelli for their ever-continuing work on Black's jupyter support
    • @jalaziz for cleaning up our Pyinstaller CD workflow
    • @hauntsaninja for helping us drop the regex dependency

    And also congrats to first contributors!

    • @MatthewScholefield made their first contribution in https://github.com/psf/black/pull/2631
    • @AshIsbitt made their first contribution in https://github.com/psf/black/pull/2632
    • @kalbasit made their first contribution in https://github.com/psf/black/pull/2638
    • @danieleades made their first contribution in https://github.com/psf/black/pull/2653
    • @danielsparing made their first contribution in https://github.com/psf/black/pull/2630
    • @tanvimoharir made their first contribution in https://github.com/psf/black/pull/2343
    Source code(tar.gz)
    Source code(zip)
    black_linux(16.92 MB)
    black_macos(7.19 MB)
    black_windows.exe(7.71 MB)
  • 21.11b1(Nov 18, 2021)

  • 21.11b0(Nov 17, 2021)

    Black

    • Warn about Python 2 deprecation in more cases by improving Python 2 only syntax detection (#2592)
    • Add experimental PyPy support (#2559)
    • Add partial support for the match statement. As it's experimental, it's only enabled when --target-version py310 is explicitly specified (#2586)
    • Add support for parenthesized with (#2586)
    • Declare support for Python 3.10 for running Black (#2562)

    Integrations

    • Fixed vim plugin with Python 3.10 by removing deprecated distutils import (#2610)
    • The vim plugin now parses skip_magic_trailing_comma from pyproject.toml (#2613)
    Source code(tar.gz)
    Source code(zip)
    black_linux(17.60 MB)
    black_macos(7.44 MB)
    black_windows.exe(7.93 MB)
  • 21.10b0(Nov 1, 2021)

    Black

    • Document stability policy, that will apply for non-beta releases (#2529)
    • Add new --workers parameter (#2514)
    • Fixed feature detection for positional-only arguments in lambdas (#2532)
    • Bumped typed-ast version minimum to 1.4.3 for 3.10 compatiblity (#2519)
    • Fixed a Python 3.10 compatibility issue where the loop argument was still being passed even though it has been removed (#2580)
    • Deprecate Python 2 formatting support (#2523)

    Blackd

    • Remove dependency on aiohttp-cors (#2500)
    • Bump required aiohttp version to 3.7.4 (#2509)

    Black-Primer

    • Add primer support for --projects (#2555)
    • Print primer summary after individual failures (#2570)

    Integrations

    • Allow to pass target_version in the vim plugin (#1319)
    • Install build tools in docker file and use multi-stage build to keep the image size down (#2582)
    Source code(tar.gz)
    Source code(zip)
    black_linux(17.61 MB)
    black_macos(7.43 MB)
    black_windows.exe(7.90 MB)
  • 21.9b0(Sep 14, 2021)

  • 21.8b0(Aug 29, 2021)

    Black

    • Add support for formatting Jupyter Notebook files (#2357)
    • Move from appdirs dependency to platformdirs (#2375)
    • Present a more user-friendly error if .gitignore is invalid (#2414)
    • The failsafe for accidentally added backslashes in f-string expressions has been hardened to handle more edge cases during quote normalization (#2437)
    • Avoid changing a function return type annotation's type to a tuple by adding a trailing comma (#2384)
    • Parsing support has been added for unparenthesized walruses in set literals, set comprehensions, and indices (#2447).
    • Pin setuptools-scm build-time dependency version (#2457)
    • Exclude typing-extensions version 3.10.0.1 due to it being broken on Python 3.10 (#2460)

    Blackd

    • Replace sys.exit(-1) with raise ImportError as it plays more nicely with tools that scan installed packages (#2440)

    Integrations

    • The provided pre-commit hooks no longer specify language_version to avoid overriding default_language_version (#2430)
    Source code(tar.gz)
    Source code(zip)
    black_linux(16.54 MB)
    black_macos(7.36 MB)
    black_windows.exe(7.89 MB)
  • 21.7b0(Jul 16, 2021)

    Black

    • Configuration files using TOML features higher than spec v0.5.0 are now supported (#2301)
    • Add primer support and test for code piped into black via STDIN (#2315)
    • Fix internal error when FORCE_OPTIONAL_PARENTHESES feature is enabled (#2332)
    • Accept empty stdin (#2346)
    • Provide a more useful error when parsing fails during AST safety checks (#2304)

    Docker

    • Add new latest_release tag automation to follow latest black release on docker images (#2374)

    Integrations

    • The vim plugin now searches upwards from the directory containing the current buffer instead of the current working directory for pyproject.toml. (#1871)
    • The vim plugin now reads the correct string normalization option in pyproject.toml (#1869)
    • The vim plugin no longer crashes Black when there's boolean values in pyproject.toml (#1869)
    Source code(tar.gz)
    Source code(zip)
    black_linux(16.35 MB)
    black_macos(7.30 MB)
    black_windows.exe(7.85 MB)
  • 21.6b0(Jun 10, 2021)

    Black

    • Fix failure caused by fmt: skip and indentation (#2281)
    • Account for += assignment when deciding whether to split string (#2312)
    • Correct max string length calculation when there are string operators (#2292)
    • Fixed option usage when using the --code flag (#2259)
    • Do not call uvloop.install() when Black is used as a library (#2303)
    • Added --required-version option to require a specific version to be running (#2300)
    • Fix incorrect custom breakpoint indices when string group contains fake f-strings (#2311)
    • Fix regression where R prefixes would be lowercased for docstrings (#2285)
    • Fix handling of named escapes (\N{...}) when --experimental-string-processing is used (#2319)
    Source code(tar.gz)
    Source code(zip)
    black_linux(16.47 MB)
    black_macos(7.12 MB)
    black_windows.exe(7.82 MB)
  • 21.5b2(May 31, 2021)

    Black

    • A space is no longer inserted into empty docstrings (#2249)
    • Fix handling of .gitignore files containing non-ASCII characters on Windows (#2229)
    • Respect .gitignore files in all levels, not only root/.gitignore file (apply .gitignore rules like git does) (#2225)
    • Restored compatibility with Click 8.0 on Python 3.6 when LANG=C used (#2227)
    • Add extra uvloop install + import support if in python env (#2258)
    • Fix --experimental-string-processing crash when matching parens are not found (#2283)
    • Make sure to split lines that start with a string operator (#2286)
    • Fix regular expression that black uses to identify f-expressions (#2287)

    Blackd

    • Add a lower bound for the aiohttp-cors dependency. Only 0.4.0 or higher is supported. (#2231)

    Packaging

    • Release self-contained x86_64 MacOS binaries as part of the GitHub release pipeline (#2198)
    • Always build binaries with the latest available Python (#2260)

    Documentation

    • Add discussion of magic comments to FAQ page (#2272)
    • --experimental-string-processing will be enabled by default in the future (#2273)
    • Fix typos discovered by codespell (#2228)
    • Fix Vim plugin installation instructions. (#2235)
    • Add new Frequently Asked Questions page (#2247)
    • Fix encoding + symlink issues preventing proper build on Windows (#2262)
    Source code(tar.gz)
    Source code(zip)
    black_linux(16.47 MB)
    black_macos(7.12 MB)
    black_windows.exe(7.82 MB)
  • 21.5b1(May 10, 2021)

  • 21.5b0(May 4, 2021)

  • 21.4b2(Apr 28, 2021)

  • 21.4b1(Apr 27, 2021)

    Black

    • Fix crash on docstrings ending with "\ ". (#2142)

    • Fix crash when atypical whitespace is cleaned out of dostrings (#2120)

    • Reflect the --skip-magic-trailing-comma and --experimental-string-processing flags in the name of the cache file. Without this fix, changes in these flags would not take effect if the cache had already been populated. (#2131)

    • Don't remove necessary parentheses from assignment expression containing assert / return statements. (#2143)

    Packaging

    • Bump pathspec to >= 0.8.1 to solve invalid .gitignore exclusion handling
    Source code(tar.gz)
    Source code(zip)
    black.elf(13.84 MB)
    black.exe(7.64 MB)
  • 21.4b0(Apr 25, 2021)

    Black

    • Fixed a rare but annoying formatting instability created by the combination of optional trailing commas inserted by Black and optional parentheses looking at pre-existing "magic" trailing commas. This fixes issue #1629 and all of its many many duplicates. (#2126)

    • Black now processes one-line docstrings by stripping leading and trailing spaces, and adding a padding space when needed to break up """". (#1740)

    • Black now cleans up leading non-breaking spaces in comments (#2092)

    • Black now respects --skip-string-normalization when normalizing multiline docstring quotes (#1637)

    • Black no longer removes all empty lines between non-function code and decorators when formatting typing stubs. Now Black enforces a single empty line. (#1646)

    • Black no longer adds an incorrect space after a parenthesized assignment expression in if/while statements (#1655)

    • Added --skip-magic-trailing-comma / -C to avoid using trailing commas as a reason to split lines (#1824)

    • fixed a crash when PWD=/ on POSIX (#1631)

    • fixed "I/O operation on closed file" when using --diff (#1664)

    • Prevent coloured diff output being interleaved with multiple files (#1673)

    • Added support for PEP 614 relaxed decorator syntax on python 3.9 (#1711)

    • Added parsing support for unparenthesized tuples and yield expressions in annotated assignments (#1835)

    • use lowercase hex strings (#1692)

    • added --extend-exclude argument (PR #2005)

    • speed up caching by avoiding pathlib (#1950)

    • --diff correctly indicates when a file doesn't end in a newline (#1662)

    • Added --stdin-filename argument to allow stdin to respect --force-exclude rules (#1780)

    • Lines ending with fmt: skip will now be not formatted (#1800)

    • PR #2053: Black no longer relies on typed-ast for Python 3.8 and higher

    • PR #2053: Python 2 support is now optional, install with python3 -m pip install black[python2] to maintain support.

    • Exclude venv directory by default (#1683)

    • Fixed "Black produced code that is not equivalent to the source" when formatting Python 2 docstrings (#2037)

    Packaging

    • Self-contained native Black binaries are now provided for releases via GitHub Releases (#1743)
    Source code(tar.gz)
    Source code(zip)
    black.elf(13.84 MB)
    black.exe(7.64 MB)
  • 20.8b1(Aug 26, 2020)

  • 20.8b0(Aug 26, 2020)

Robocop is a tool that performs static code analysis of Robot Framework code.

Robocop Introduction Documentation Values Requirements Installation Usage Example Robotidy FAQ Watch our talk from RoboCon 2021 about Robocop and Robo

marketsquare 116 May 26, 2022
CodeAnalysis - Static Code Analysis: a code comprehensive analysis platform

TCA, Tencent Cloud Code Analysis English | 简体中文 What is TCA Tencent Cloud Code A

Tencent 1.1k May 27, 2022
Turn your Python and Javascript code into DOT flowcharts

Notes from 2017 This is an older project which I am no longer working on. It was built before ES6 existed and before Python 3 had much usage. While it

Scott Rogowski 2.5k May 26, 2022
Find dead Python code

Vulture - Find dead code Vulture finds unused code in Python programs. This is useful for cleaning up and finding errors in large code bases. If you r

Jendrik Seipp 2.1k May 25, 2022
Code audit tool for python.

Pylama Code audit tool for Python and JavaScript. Pylama wraps these tools: pycodestyle (formerly pep8) © 2012-2013, Florent Xicluna; pydocstyle (form

Kirill Klenov 892 May 23, 2022
A static type analyzer for Python code

pytype - ? ✔ Pytype checks and infers types for your Python code - without requiring type annotations. Pytype can: Lint plain Python code, flagging c

Google 3.7k May 18, 2022
Print a directory tree structure in your Python code.

directory-structure Print a directory tree structure in your Python code. Download You can simply: pip install directory-structure Or you can also: Cl

Gabriel Stork 40 Mar 9, 2022
Python package to parse and generate C/C++ code as context aware preprocessor.

Devana Devana is a python tool that make it easy to parsing, format, transform and generate C++ (or C) code. This tool uses libclang to parse the code

null 5 Apr 3, 2022
Find usage statistics (imports, function calls, attribute access) for Python code-bases

Python Library stats This is a small library that allows you to query some useful statistics for Python code-bases. We currently report library import

Francisco Massa 13 May 2, 2022
A very minimalistic python module that lets you track the time your code snippets take to run.

Clock Keeper A very minimalistic python module that lets you track the time your code snippets take to run. This package is available on PyPI! Run the

Rajdeep Biswas 1 Jan 19, 2022
This is a Python program to get the source lines of code (SLOC) count for a given GitHub repository.

This is a Python program to get the source lines of code (SLOC) count for a given GitHub repository.

Nipuna Weerasekara 2 Mar 10, 2022
coala provides a unified command-line interface for linting and fixing all your code, regardless of the programming languages you use.

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." ― John F. Woods coala provides a

coala development group 3.3k May 22, 2022
Guesslang detects the programming language of a given source code

Detect the programming language of a source code

Y. SOMDA 542 May 27, 2022
Learning source code review, spot vulnerability, find some ways how to fix it.

Learn Source Code Review Learning source code review, spot vulnerability, find some ways how to fix it. WordPress Plugin Authenticated Stored XSS on C

Shan 11 Sep 1, 2021
An app to show the total number of lines of code written by an user.

Lines of code Have you ever wondered how many lines of code you wrote in github? This tool will calculate it for you! To calculate the total number of

B.Jothin kumar 10 Jan 26, 2022
Metrinome is an all-purpose tool for working with code complexity metrics.

Overview Metrinome is an all-purpose tool for working with code complexity metrics. It can be used as both a REPL and API, and includes: Converters to

null 20 Jan 12, 2022
A simple stopwatch for measuring code performance with static typing.

A simple stopwatch for measuring code performance. This is a fork from python-stopwatch, which adds static typing and a few other things.

Rafael 2 Feb 18, 2022
pycallgraph is a Python module that creates call graphs for Python programs.

Project Abandoned Many apologies. I've stopped maintaining this project due to personal time constraints. Blog post with more information. I'm happy t

gak 1.6k May 24, 2022
Inspects Python source files and provides information about type and location of classes, methods etc

prospector About Prospector is a tool to analyse Python code and output information about errors, potential problems, convention violations and comple

Python Code Quality Authority 1.6k May 23, 2022