[Numpy-discussion] Should ndarray be a context manager?

Nathaniel Smith njs at pobox.com
Tue Dec 9 18:59:41 EST 2014


On 9 Dec 2014 15:03, "Sturla Molden" <sturla.molden at gmail.com> wrote:
>
>
> I wonder if ndarray should be a context manager so we can write
> something like this:
>
>
>     with np.zeros(n) as x:
>        [...]
>
>
> The difference should be that __exit__ should free the memory in x (if
> owned by x) and make x a zero size array.

Regardless of whether this functionality is provided as part of numpy, I
don't much like the idea of putting __enter__ and __exit__ methods on
ndarray itself. It's just very confusing - I had no idea what 'with arr'
would mean when I saw the thread subject. It's much clearer and easier to
document if one uses a special context manager just for this, like:

with tmp_zeros(...) as arr:
    ...

This should be pretty trivial to implement. AFAICT you don't need any
complicated cython, you just need:

@contextmanager
def tmp_zeros(*args, **kwargs):
    arr = np.zeros(*args, **kwargs)
    try:
        yield arr
    finally:
        arr.resize((0,), check_refs=False)

Given how intrinsically dangerous this is, and how easily it can be
implemented using numpy's existing public API, I think maybe we should
leave this for third-party daredevils instead of implementing it in numpy
proper.

-n
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141209/a984a78c/attachment.html>


More information about the NumPy-Discussion mailing list