<p dir="ltr">On 9 Dec 2014 15:03, "Sturla Molden" <<a href="mailto:sturla.molden@gmail.com">sturla.molden@gmail.com</a>> wrote:<br>
><br>
><br>
> I wonder if ndarray should be a context manager so we can write<br>
> something like this:<br>
><br>
><br>
>     with np.zeros(n) as x:<br>
>        [...]<br>
><br>
><br>
> The difference should be that __exit__ should free the memory in x (if<br>
> owned by x) and make x a zero size array.</p>
<p dir="ltr">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:</p>
<p dir="ltr">with tmp_zeros(...) as arr:<br>
    ...</p>
<p dir="ltr">This should be pretty trivial to implement. AFAICT you don't need any complicated cython, you just need:</p>
<p dir="ltr">@contextmanager<br>
def tmp_zeros(*args, **kwargs):<br>
    arr = np.zeros(*args, **kwargs)<br>
    try:<br>
        yield arr<br>
    finally:<br>
        arr.resize((0,), check_refs=False)</p>
<p dir="ltr">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.</p>
<p dir="ltr">-n</p>