Search code examples
pythonarraysnumpypretty-print

Local scope for numpy set_printoptions


np.set_printoptions allows to customize the pretty printing of numpy arrays. For different use cases, however, I would like to have different printing options.

Ideally, this would be done without having to redefine the whole options each time. I was thinking on using a local scope, something like:

with np.set_printoptions(precision=3):
    print my_numpy_array

However, set_printoptions doesn't seem to support with statements, as an error is thrown (AttributeError: __exit__). Is there any way of making this work without creating your own pretty printing class? This is, I know that I can create my own Context Manager as:

class PrettyPrint():
    def __init__(self, **options):
        self.options = options

    def __enter__(self):
        self.back = np.get_printoptions()
        np.set_printoptions(**self.options)

    def __exit__(self, *args):
        np.set_printoptions(**self.back)

And use it as:

>>> print A
[ 0.29276529 -0.01866612  0.89768998]

>>> with PrettyPrint(precision=3):
        print A
[ 0.293 -0.019  0.898]

Is there, however, something more straightforward (preferably already built-in) than creating a new class?


Solution

  • Try

     np.array_repr(x, precision=6, suppress_small=True)
    

    Or one of the related functions that take keywords like precision. Looks like it can control many, if not all, of the print options.