Share a very useful Python gadget, this article is not my original, the original text is from Introducing PrettyPrinter for Python, the translation source can not be found, please remind me if any students know.


PrettyPrinter is a powerful, syntax-highlighting, descriptive, beautification print package in Python 3.6 and above. It uses an improved Wadler-Leijen layout algorithm, Prettier for JavaScript, PrettyPreinter. Rb for Ruby, and Prettyprinter for Haskell, anti-wl-pprint for JavaScript, Prettier for Ruby, and prettyPreinter IPython’s ipython.lib. pretty similar. Python’s PrettyPrinter sets the strengths of the above, and continues to improve on this basis, so it has become the most powerful Python beautification output tool.

Here is a screenshot of the output using PrettyPrinter:



Why does Python need additional embellished print packages?

Printing data to the screen is the most basic interface for programmer and numerical interaction during program execution, whether the IDE or the developer runs commands manually. Improving the interface can help improve the development experience and productivity. Both Python itself and third-party libraries provide a number of tools to do this:

  • The __repr__ and __str__ underscore methods return plain strings. __repr__ should return as syntactically correct a Python expression as possible, and is most commonly used to assert failure and print the results of console calculations. Because it is entirely based on string formatting, it does not have the ability to beautify printing.
  • The pprint module in the standard library provides beautification printing for built-in data types such as dicts, Lists, tuples, sets, and Frozensets. It applies a __repr__ method to a user-defined class instance. However, it uses a very greedy layout algorithm, resulting in problems with beautification printing in many cases. Since custom beautification printing is limited by __repr__, the usefulness of pPrint is limited to built-in data types.
  • The third-party library Pprintpp, an improvement and alternative to pprint, can also optimize the output, but like pprint is limited by the code beautification definition used by __repr__.
  • The default print module in IPython, ipython.lib. pretty, is aimed at a more advanced alternative to pprint. Compared to PPrint, it performs better in many ways: the algorithm can beautify the output in most cases, and it provides a definition tool for beautifying the output for user-defined types, which can be combined well with other parts of the output. However, in order to implement your own embellished printing, you need to understand layout algorithms. In addition, the API has some inherent side effects: calling the beautification printing tool pushes the data directly into the layout buffer, not allowing the original layout to make a preliminary inspection of the data.

None of the tools above met my requirements for a better printing experience, so I started making the following improvements:

  • Implement an algorithm that beautifies printing as much as possible, even at the expense of efficiency. Spending a tenth of a second to beautify the output is very cost-effective, because it will save you two seconds when you need to find the data you need in the results.
  • Implement a super simple, descriptive interface to achieve user – defined beautification printing tools. Python members almost never override the __repr__ method because it is painful; Few people want to write neat printing rules for user-defined types unless the type is very simple.
  • Implement syntax highlighting that does not break on invalid Python syntax. Not all __repr__ methods return valid syntax, and normal syntax highlighting can be interrupted if a syntax error occurs.

I was very surprised by the experience with the new code beautification pack. The algorithm works well and the efficiency meets the requirements. Customizing the beautification rules is easy, just by knowing the two descriptive functions register_pretty and pretty_call. Syntax highlighting looks nice and is not interrupted by invalid syntax. Syntax highlighting, in particular, makes it hard to go back to the normal beautification printing tool, which greatly improves the development experience for programmers.

The most interesting improvement is the descriptive API, and here’s how it works.

Simple, descriptive APIS

Defining output beautification methods in a PrettyPrinter is primarily based on (create) function calls. All non-character Python values need to be represented as function results. The mainstay of the library is pretty_call, which allows you to describe what type of function call PrettyPrinter should print. Here is an example of a pretty_call:


PrettyPrinter processes the original layout similar to the following statement:


The first parameter CTX allows the user to control the nested data in the [5,3,6,1] list in the case against which the True value of the reverse parameter is rendered. In most cases, just use the default values.)

Now that we’ve seen how to use Pretty_call, let’s define our own types.


Using the register_pretty modifier, you can define beautification for the MyClass class:


The output of cpprint is as follows:


Click on the PrettyPrinter Definition Code for Standard Library Types to see more examples.

Representation with state instances

One drawback of calling functions is that they don’t represent stateful instances very well. Often you want to output some additional information to indicate the state of the instance. PrettyPrinter solves this problem with explanatory comments, and I’m pleased with its powerful feature. Annotate Python values (or the original layout representing Python values) with comments that magically appear in the output.

Suppose we define a Connection class that contains both its connected and disconnected states:


If you want the following output:


This can be done with the following definition:


conclusion

I’ve really enjoyed using PrettyPrinter as part of my development kit. A single article can only share a few rough points, there are many interesting parts to explore, I highly recommend you try it! It works even better in IPython, because all results in an interactive interpreter environment can be automatically printed using PrettyPrinter. Instructions for setting this command are provided in the documentation.

Click Source Code on GitHub to see the project’s source code, documented on readthedocs.io (which may be a little sketchy at the moment). The package includes ready-made definitions for Django models, QuerySets, and all classes created using the Attrs package. So if you happen to use one of these, no doubt you’ll want to give it a try!


If you want to learn more about learning Python, you can take a look at the hundreds of points we spent over a month compiling over hundreds of hours:

Notes for the basic Python tutorial in Python Automation from beginner to Master