[Python-ideas] Replace option set/get methods through the standard library with a ChainMap; add a context manager to ChainMap

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Sep 12 12:04:29 CEST 2013


On 11 September 2013 23:18, Neil Girdhar <mistersheik at gmail.com> wrote:
>
> With numpy print options, for example, the usual pattern is to save some of
> the print options, set some of them, and then restore the old options.  Why
> not expose the options as a ChainMap called numpy.printoptions?  ChainMap
> could then expose a context manager that pushes a new dictionary on entry
> and pops it on exit via, say, child_context that accepts a dictionary.  Now,
> instead of:
>
> saved_precision = np.get_printoptions()['precision']
> np.set_printoptions(precision=23)
> do_something()
> np.set_printoptions(precision=saved_precision)
>
> You can do the same with a context manager, which I think is stylistically
> better (as it's impossible to forget to reset the option, and no explicit
> temporary invades the local variables):
>
> with np.printoptions.child_context({'precision', 23}):
>     do_something()

You can write this yourself If you like (untested):

from contextlib import contextmanager

@contextmanager
def print_options(**opts):
    oldopts = np.get_print_options()
    newopts = oldopts.copy()
    newopts.update(opts)
    try:
        np.set_print_options(**newopts)
        yield
    finally:
        np.set_print_options(**oldopts)

with print_options(precision=23):
    do_something()

Generally speaking numpy doesn't use context managers much. You may be
right that it should use them more but this isn't the right place to
make that suggestion since numpy is not part of core Python or of the
standard library. I suggest that you ask this on the scipy-users
mailing list.


Oscar


More information about the Python-ideas mailing list