如何用自定义类替换h5py.AttributeManager?

时间:2018-10-10 23:46:26

标签: python-3.x h5py

我想在hdf5属性中存储一个令人费解的Quantity

此刻我正在做什么:

from astropy import units
import h5py


length_1 = 5.3 * units.meter

# -- Write attribute ----------
with h5py.File("./temp.hdf5", "w") as data:
    # write value
    data.attrs.create("length", length_1.value)
    # write unit  
    data.attrs.create("lengthUnit", length_1.unit.to_string())

# -- Read attribute -----------
with h5py.File("./temp.hdf5", "r") as data:
    # read value
    lengthValue = data.attrs["length"]
    # read unit
    lengthUnit = data.attrs["lengthUnit"]

    # recreate length as Quantity
    length_2 = lengthValue * units.Unit(lengthUnit)

但是,如我在这里所做的那样,如果我可以修改AttributeManager的getter / setter流程以处理任何Quantity会很有帮助。 例如。

class QuantityAttributeManager(h5py.AttributeManager):

    def __init__(self, parent):
        super().__init__(parent)

    # __setitem__ uses create
    def create(self, name, data, shape=None, dtype=None):

        if isinstance(data, units.Quantity):
            super().create(
                    name,
                    data.value
                    )
            super().create(
                    "{:s}Unit".format(name),
                    data.unit.to_string().encode("utf-8")
                    )
        else:
            super().create(name, data, shape, dtype)

    # def __getitem__

    # [...]

with h5py.File("./temp.hdf5", "w") as data:
    # really this should be:
    #    data.attrs["length"] = length
    # and this is where the problem lies
    attr = QuantityAttributeManager(data["/"])
    attr["length"] = length_1

    print(list(attr.keys()))  # ['length', 'lengthUnit']

.attrs属性定义为([source]

@property
def attrs(self):
    """ Attributes attached to this object """
    from . import attrs
    with phil:
        return attrs.AttributeManager(self)
HLObjectDataset继承的Group

File继承了Group,但覆盖了.attrs

我看到的最好的选择是将from . import attrs行重定向为使用QuantityAttributeManager,但是我不确定如何。 (最好不要太客气。)

1 个答案:

答案 0 :(得分:0)

一种可行的解决方案可能是猴子补丁,但随后将始终使用新的属性管理器。

h5py._hl.attrs.AttributeManager = QuantityAttributeManager

with h5py.File("./temp.hdf5", "w") as data:
    data.attrs["length"] = length

    print(list(data.attrs.keys()))  # ['length', 'lengthUnit']