Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will explode if I import `pprint()` over `print()`?

I notice that I can do this and get away with it, at least at first glance:

from pprint import pprint as print

Convenient. But I have a bad feeling about this. What sort of grue is going to eat me if I try this in a nontrivial program?

like image 677
Andrew Avatar asked Jan 27 '23 21:01

Andrew


1 Answers

Beware that pprint is meant for dumping Python data structures, as it always prints the output of the __repr__ method of each object in the data structures pass to it, and is therefore not very suitable as a replacement to print:

>>> b = '''Hemingway's "The Old Man and the Sea"'''
>>> print(b)
Hemingway's "The Old Man and the Sea"
>>> pprint(b)
'Hemingway\'s "The Old Man and the Sea"'

So if you replace the built-in print function with pprint and want to print some readable messages, you would find the output looking funny with all these unintended quotes and escape sequences.

like image 89
blhsing Avatar answered Jan 31 '23 09:01

blhsing