On 9 Dec 2014 15:03, "Sturla Molden" <sturla.mol...@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
_______________________________________________
NumPy-Discussion mailing list
NumPy-Discussion@scipy.org
http://mail.scipy.org/mailman/listinfo/numpy-discussion

Reply via email to