5

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?

Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67
  • 1
    There is a more compact way to make the context manager, [shown here](http://stackoverflow.com/a/2891805/190597). – unutbu Jun 27 '16 at 10:14
  • @unutbu Didn't know about `contextlib` (nor that answer) thank you! But it still implies defining a new function.. I guess is better than nothing. – Imanol Luengo Jun 27 '16 at 10:32

2 Answers2

5

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thanks! It is not exactly equivalent to the context manager, but is much more readable (and shorter) for my purposes. – Imanol Luengo Jun 27 '16 at 15:14
  • 1
    `np.core.arrayprint.py` is the Python code for all these formatting operations, including the `set_printoptions`. It was probably written before `contexts` were widely used in Python. – hpaulj Jun 27 '16 at 16:15
5

So based on the link given by @unutbu, instead of using

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

we should use:

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

which works on my case. If things don't seem changed, try to manipulate other parameters for print options, e.g. linewidth = 125, edgeitems = 7, threshold = 1000 and so forth.

Jason
  • 3,166
  • 3
  • 20
  • 37