[Numpy-discussion] problem with WRITEABLE flag and array interface

Nathaniel Smith njs@pobox....
Fri Feb 13 05:22:00 CST 2009

I'm using rpy2 to access the R statistical programming runtime from
Python, and one of rpy2's nice features is that wrappers for R arrays
support the Python array interface (via __array_struct__), so that one
can conveniently cast them to numpy arrays and edit them in place.

But this seems to expose a bug in numpy's WRITEABLE flag handling.
Such arrays start out writeable:

  >>> a = np.asarray(r)
  >>> a.flags["WRITEABLE"]

And you can toggle them unwriteable:

  >>> a.flags["WRITEABLE"] = False

But then you are stuck! You cannot make the array writeable again:

  >>> a.flags["WRITEABLE"] = True
  ValueError: cannot set WRITEABLE flag to True of this array

This may seem rather trivial, but it's completely broken my API
design... the problem is that R has somewhat complex rules for when
you can write to an array and when you cannot (because of
copy-on-write stuff going on behind the scenes), and I wanted to
reflect that in my high-level API (for people who don't want to know
about R's COW minutiae) by toggling the WRITEABLE flag in a controlled
way. But I can't. Help?

Self-contained test case:

class Fraud(object):
f = Fraud()
a = np.array([1, 2, 3])
f.__array_interface__ = a.__array_interface__
f_asarray = np.asarray(f)
assert f_asarray.flags["WRITEABLE"] = True
f_asarray.flags["WRITEABLE"] = False
f_asarray.flags["WRITEABLE"] = True    # Fails

-- Nathaniel

More information about the Numpy-discussion mailing list