0

I'm writing a class that has an attribute of numpy array type. Since I'd like it to be read-only, I set its WRITABLE flag to be false:

import numpy as np
class MyClass:
    def __init__(self):
        self.my_array = np.zeros(5)
        self.my_array.setflags(write=False)

After doing some other stuff, I dump MyClass into a pickle file:

pickle.dump(self, writer)

Later, I load it using x = pickle.load(reader), but then the WRITABLE flag is true. How can I make the pickle dump to preserve the numpy array WRITABLE flag?

anemone
  • 51
  • 5
  • Your constructor only runs when you create an instance of your object. How did you find out that it didn't set the flag? – Mazdak Aug 11 '16 at 16:54
  • It's not surprising that the flags aren't preserved, considering that most of them represent properties that wouldn't be preserved by the pickling/unpickling process. For example, C_CONTIGUOUS and OWNDATA. – user2357112 Aug 11 '16 at 17:01

1 Answers1

0

For pickling arrays, numpy uses the np.save function. Details of this save are in np.lib.format file. This format saves a header and a byte representation of the data buffer. The content of header is a dictionary.

In [1212]: np.lib.format.header_data_from_array_1_0(x)
Out[1212]: {'descr': '<i4', 'fortran_order': False, 'shape': (2, 3)}
In [1213]: np.lib.format.header_data_from_array_1_0(u)
Out[1213]: {'descr': '<c16', 'fortran_order': False, 'shape': (4,)}

As you can see it does not save the whole FLAGS attribute, just info on the order.

Class pickling can be customized with __reduce__ and __setstate__ methods.

See also

How can I make np.save work for an ndarray subclass?

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353