I use h5py to access HDF5 files and store h5py File objects in a class. But I experience strange behavior when trying to reassign the private variable of the h5py file instance to a new one:
class MyClass:
def __init__(self, filename):
self.h5file = None
self.filename = filename
def vartest(self):
self.h5file = h5py.File(self.filename, 'r')
print self.h5file
self.h5file.close()
print self.h5file
newh5file = h5py.File(self.filename, 'r')
print newh5file
self.h5file = newh5file
print self.h5file
print newh5file
def main():
filename = sys.argv[1]
mycls = MyClass(filename)
mycls.vartest()
Conclusion:
<HDF5 file "test.h5" (mode r, 92.7M)>
<Closed HDF5 file>
<HDF5 file "test.h5" (mode r, 92.7M)>
<Closed HDF5 file>
<Closed HDF5 file>
Attempting to update the instance variable with the newly opened h5py File seems to have somehow affected the state of the object by closing it. Regardless of the implementation on the h5py side, I don't see how this behavior makes sense from my understanding of the Python language (i.e., overloading the assignment operator).
This example starts with Python 2.6.5 and h5py 1.3.0. If you want to try this example, but you don’t have an HDF5 file sitting around, you can simply change the file access mode from 'r' to 'a'.