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

Viewed 127

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?

2 Answers

Nothing will explode, because this import will only change your local namespace.

Namespaces are one honking great idea -- let's do more of those!

You may go ahead and do it, without fear of breaking other namespaces or being eaten by grues.

Do be aware, however, that the pprint call signature is different from print, so it's possible some print lines within the containing module may need to be adjusted. My recommendation is to import it under the usual name, pprint, and use the find/replace features of your text editor to change existing print calls accordingly.

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.

Related