avatarChristopher Tao

Summary

The article introduces the Python code formatter "Black," which automatically reformats code to adhere to the PEP 8 style guide, enhancing code readability and consistency.

Abstract

The article "Treat Yourself Using The 'Black' Library When Writing Python Code" discusses the benefits of using the "Black" Python library for code formatting. It emphasizes the importance of well-formatted code for readability and maintainability, especially for those without a programming background. "Black" ensures that code complies with PEP 8 guidelines, simplifying the process of writing consistent and readable Python code. The article provides a step-by-step guide on installing "Black," demonstrates its basic usage with before-and-after examples, and highlights some of its useful command-line interface (CLI) arguments, such as reformatting code snippets, performing dry runs to check code format without changing it, and showing the differences that would be changed. The author concludes by encouraging the use of "Black" to improve code quality and suggests considering Medium Membership to support writers who provide helpful content.

Opinions

  • The author believes that "Black" can help developers, regardless of their background, to write code that is consistent with PEP 8 standards.
  • It is implied that Python's use of indentation helps in writing more readable code, but "Black" is necessary for ensuring adherence to formatting guidelines.
  • The author suggests that manually formatting code is less efficient than using a tool like "Black," which can automatically format code and save time.
  • The article conveys that using "Black" can improve the overall quality of Python code by making it more uniform and easier to maintain.
  • By providing examples of "Black's" usage and effects, the author positively endorses the library as a valuable tool for Python developers.
  • The author encourages readers to support content creators by joining Medium Membership, indicating a belief in the value of community support for writers.
Image by Pfüderi from Pixabay

Treat Yourself Using The “Black” Library When Writing Python Code

The easiest way to have a “single format of correct” code

Have you ever copy-pasted some example code from library documentation or Stack Overflow? Or maybe you do not have a pure programmer background so you’re not trained to write perfectly formatted code? Do you want to improve your code readability to impress others?

One of the benefits of Python programming language is that it uses indentation to indicate the level of nesting of code blocks. So, it is relatively more difficult to write some “unreadable” code in terms of the format. However, it doesn’t mean that all the Python codes must be formatted. There is no programming language that can create so many constraints to force users to write formatted code, and I don’t that’s a good idea because it will be too hard to use.

In this article, I’ll introduce a Python library called “Black”. It can help us to format our code in different ways. All the styles will comply with the PEP 8 guide. Let’s start to create consistent and readable formatted code now!

1. Basic Usage

Image by Nat Aggiato from Pixabay

Before we can start to use the library, we need to install it using pip as follows.

pip install black

Let's prepare a bad example as follows.

def my_function(a=1,b=2,c=3,d=4):
    my_list = [a, 
               b, 
               c, 
               d]
    return sum(my_list)
if True: print(my_function())

The code above can definitely run, but there are many problems.

  1. The parameters in the function my_function are separated by commas but there is no whitespace after the commas.
  2. The items in the list my_list are presented vertically. It might be OK in some cases but absolutely not following the guidelines of PEP 8.
  3. There are no new lines between the function definition and the if-statement, which will create impacts on the readability.
  4. The if-statement was written in a single line. This is valid code but not good for readability.

I will save the code into a file called example1.py. We can verify the bad example as follows.

If you like, you can also verify that this Python script is definitely runnable.

Then, let’s use the black library to format the file. The simplest way of doing this is to use the command-line interface (CLI) as follows.

$ black example1.py 

It tells us the file is reformatted. Now, let’s verify the outcome.

def my_function(a=1, b=2, c=3, d=4):
    my_list = [a, b, c, d]
    return sum(my_list)


if True:
    print(my_function())

Yes! All the 4 problems mentioned before were fixed.

Have you noticed it mentioned “1 file reformatted”? That’s right. If we provide a directory, the black library will reformat all the Python scripts in the directory.

$ black my_dir/

The above example shows that we can reformat all the files in the current directory. Also, if one file is already in perfect format, black will tell us it is left unchanged.

2. Some Useful CLI Arguments/Flags

Image by Bruno /Germany from Pixabay

Like other CLI tools, black also has many arguments to provide more fancy functions. I’ll pick up some that I think would be useful and introduce them in this section.

2.1 Reformat code snippet

Let’s come to another topic. Most of the time we probably don’t want to be bothered with reformatting the file again and again. One typical scenario might be that we copied a function or a piece of code from documentation or Stack Overflow. (No shame at all, most developers are doing so :). However, the format might not be consistent with our code, or the code loses its format for some reason.

In this case, we don’t have to paste the code into a file and reformat it. We can do this using the --code argument on the fly in the console.

For example, the print() function can be formatted as follow.

$ black --code "print ( 'hello, world' )"

Now, you can copy the reformatted code and put it in your script.

2.2 Check the format (dry run)

If we just want to check if your code complies with the PEP 8 standards without changing it, we can use the --check flag as follows.

$ black example1.py --check

Well, it tells us that it doesn’t need to be changed because example1.py had been reformatted already. However, what if it needs?

Let’s create another Python script file using the original “bad example” and name the file example2.py. Let’s verify it is the “bad example”.

Then, let’s have the “dry run”.

We can see that it says “would be reformatted”. Of course, we can also have this dry run for a directory.

$ black . --check

2.3 Show what would be changed

Curious about why your code does not comply with the standards? We can use the --diff flag to show the specific changes.

$ black example2.py --diff

Summary

Image by 育银 戚 from Pixabay

In this article, I have introduced the library black, which is a popular code formatter for Python that automatically reformats your code to conform to the PEP 8 style guide. It provides consistent and readable formatting for your code, making it easier to read and maintain.

We can use black to ensure our code is consistent, readable and maintainable. It can also be used from the command line with many useful built-in features that can be called with arguments or flags. Hope it can help you for writing better code!

If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)

Unless otherwise noted all images are by the author

Artificial Intelligence
Python
Programming
Technology
Machine Learning
Recommended from ReadMedium