Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/release/1.15.0-notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ New functions
* `np.ma.stack`, the `np.stack` array-joining function generalized to masked
arrays.

* `np.printoptions`, the context manager which sets print options temporarily
for the scope of the ``with`` block::

>>> with np.printoptions(precision=2):
... print(np.array([2.0])) / 3
[0.67]


Deprecations
============
Expand Down
39 changes: 36 additions & 3 deletions numpy/core/arrayprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from __future__ import division, absolute_import, print_function

__all__ = ["array2string", "array_str", "array_repr", "set_string_function",
"set_printoptions", "get_printoptions", "format_float_positional",
"format_float_scientific"]
"set_printoptions", "get_printoptions", "printoptions",
"format_float_positional", "format_float_scientific"]
__docformat__ = 'restructuredtext'

#
Expand Down Expand Up @@ -49,7 +49,7 @@
from .numerictypes import (longlong, intc, int_, float_, complex_, bool_,
flexible)
import warnings

import contextlib

_format_options = {
'edgeitems': 3, # repr N leading and trailing items of each dimension
Expand Down Expand Up @@ -273,6 +273,39 @@ def get_printoptions():
return _format_options.copy()


@contextlib.contextmanager
def printoptions(*args, **kwargs):
"""Context manager for setting print options.

Set print options for the scope of the `with` block, and restore the old
options at the end. See `set_printoptions` for the full description of
available options.

Examples
--------

>>> with np.printoptions(precision=2):
... print(np.array([2.0])) / 3
[0.67]

The `as`-clause of the `with`-statement gives the current print options:

>>> with np.printoptions(precision=2) as opts:
... assert_equal(opts, np.get_printoptions())

See Also
--------
set_printoptions, get_printoptions

"""
opts = np.get_printoptions()
try:
np.set_printoptions(*args, **kwargs)
yield np.get_printoptions()
finally:
np.set_printoptions(**opts)


def _leading_trailing(a, edgeitems, index=()):
"""
Keep only the N-D corners (leading and trailing edges) of an array.
Expand Down
32 changes: 32 additions & 0 deletions numpy/core/tests/test_arrayprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,5 +721,37 @@ def test_unicode_object_array():
assert_equal(repr(x), expected)


class TestContextManager(object):
def test_ctx_mgr(self):
# test that context manager actuall works
with np.printoptions(precision=2):
s = str(np.array([2.0]) / 3)
assert_equal(s, '[0.67]')

def test_ctx_mgr_restores(self):
# test that print options are actually restrored
opts = np.get_printoptions()
with np.printoptions(precision=opts['precision'] - 1,
linewidth=opts['linewidth'] - 4):
pass
assert_equal(np.get_printoptions(), opts)

def test_ctx_mgr_exceptions(self):
# test that print options are restored even if an exeption is raised
opts = np.get_printoptions()
try:
with np.printoptions(precision=2, linewidth=11):
raise ValueError
except ValueError:
pass
assert_equal(np.get_printoptions(), opts)

def test_ctx_mgr_as_smth(self):
opts = {"precision": 2}
with np.printoptions(**opts) as ctx:
saved_opts = ctx.copy()
assert_equal({k: saved_opts[k] for k in opts}, opts)


if __name__ == "__main__":
run_module_suite()