Overcoming assignment behavior with an h5py object as an instance variable

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'.

+3
2

, h5py 1.3, , HDF5 1.8.5 . , 1.8.5. , HDF5 1.8.4 , h5py 2.0.

+1

, , ():

class HLObject(object):
    def __nonzero__(self):
        register_thread()
        return self.id.__nonzero__()

class Group(HLObject, _DictCompat):
    ...

class File(Group):
    def __repr__(self):
        register_thread()
        if not self:
            return "<Closed HDF5 file>"
        return '<HDF5 file "%s" (mode %s, %s)>' % \
            (os.path.basename(self.filename), self.mode,
             _extras.sizestring(self.fid.get_filesize()))

__str__, __repr__ , __repr__ register_thread(), , self ( True False).

Python , __nonzero__ ( register_thread()), self.id.__nonzero__(), , -, False.

, , (), register_thread / self.id , .

+1

All Articles