[Python-ideas] Replace numpy get_printoptions/set_printoptions, and similar patterns with a ChainMap; add a context manager to ChainMap

Neil Girdhar mistersheik at gmail.com
Thu Sep 12 00:07:45 CEST 2013

Just to be clear, my proposal is to replace all such get/set options 
patterns throughout Python's standard library.

On Wednesday, September 11, 2013 5:13:55 PM UTC-4, Neil Girdhar wrote:
> With numpy, the usual pattern is to get_printoptions, set some of them, 
> and then restore the old options.  Why not expose the options in a ChainMap 
> as 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()
> Best,
> Neil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130911/c4a74d9f/attachment.html>

More information about the Python-ideas mailing list