Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I undo the formatting style changes that Black makes to my Python code?

Does the Python formatting tool Black have an option for undoing the formatting changes it made after it's been run? Or does it assume I'm using source control and making my own backups? This is as of December 2019 and Black version 19.3b0.

like image 631
Al Sweigart Avatar asked Dec 10 '19 00:12

Al Sweigart


People also ask

What is Python black formatting?

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.

How do I set Python to black format?

Type “format on save” at the search bar on top of the Settings tab and check the box. Search for “python formatting provider” and select “black”. Now open/create a python file, write some code and save(Ctrl+s) it to see the magic happen!

Can you break a black code?

Line breaks & binary operatorsBlack will break a line before a binary operator when splitting a block of code over multiple lines. This is so that Black is compliant with the recent changes in the PEP 8 style guide, which emphasizes that this approach improves readability.

Does formatting matter in Python?

Why code formatting matters. The main benefit to Python code formatting and investing time in developing style guides is that it makes the content easy to understand.


Video Answer


3 Answers

No it does not. It does nothing more, but reformat the files it has been passed. It's simply a well behaved Unix tool and it expects you to handle your own version control.

Its --diff option is the best you can get:

--diff

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

Source: https://github.com/psf/black#command-line-options

like image 115
ruohola Avatar answered Oct 14 '22 05:10

ruohola


Using the --diff flag, it is possible to pipe the output to patch which then emits to stdout. A one-line shellscript can be used as a wrapper, where $1 is the file that is being formatted:

black --quiet --diff "$1" | patch --quiet -o - "$1"

like image 26
alex Avatar answered Oct 14 '22 05:10

alex


Some text editors and IDEs like Pycharm allow you to simply hit cmd+Z (or whatever the undo command is within the editor) to revert back to the state before autoformatting. Also, before autoformatting you can test out what the results will be using Black Playground.

like image 41
jmdeamer Avatar answered Oct 14 '22 07:10

jmdeamer