1

I would like to know how the python pprint module handles recursion. When running this code from here:

import pprint
tmp = [[-3.3724829788320254e-06, 8.789645278006741e-05, -0.03094601113910861], [-0.0001309722558718793, -2.6760843426808773e-05, 8.351451616757592e-06, 0.9999999910301892]]

class FormatPrinter(pprint.PrettyPrinter):

    def __init__(self, formats):
        super(FormatPrinter, self).__init__(compact=True)
        self.formats = formats

    def format(self, obj, ctx, maxlvl, lvl):
        if type(obj) in self.formats:
            return self.formats[type(obj)] % obj, 1, 0
        return pprint.PrettyPrinter.format(self, obj, ctx, maxlvl, lvl)
    
FormatPrinter({float: "%0.2f", int: "%06X"}).pprint(tmp)

I get the following output in a jupyter notebook with python 3.8.12:

[[-3.3724829788320254e-06, 8.789645278006741e-05, -0.03094601113910861],
 [-0.00, -0.00, 0.00, 1.00]]

What I would expect to see is:

[[-0.00, -0.00, -0.03],
 [-0.00, -0.00, 0.00, 1.00]]

Finally what I would like to have is pretty prining without newlines and with two spaces in front of positive numbers so that the output stays aligned when printing different values.

[[-0.00, -0.00, -0.03], [-0.00, -0.00,  0.00,  1.00]]
BlGene
  • 17
  • 4

0 Answers0