diff --git a/nomad/metainfo/data_type.py b/nomad/metainfo/data_type.py index 7ee24a76bcd8368d85f366ffe088a3730180cc01..b327bc48f0e8269516bfa693a8d3323c327ead66 100644 --- a/nomad/metainfo/data_type.py +++ b/nomad/metainfo/data_type.py @@ -290,16 +290,22 @@ class Primitive(Datatype): if self.is_scalar: given_type = type(value) if given_type is np.ndarray: - given_type = value.dtype.type + if value.size != 1: + raise ValueError( + f'Cannot set {value} for the scalar quantity {self._definition}.' + ) - # no conversion and type mismatch - if self._disable_auto_conversion and given_type != self._dtype: - raise ValueError(f'Cannot set {value} for {self._definition}.') + value = value[0] + given_type = value.dtype.type # type match, no need to consider conversion if given_type == self._dtype: return value + # no conversion and type mismatch + if self._disable_auto_conversion: + raise ValueError(f'Cannot set {value} for {self._definition}.') + # conversion is allowed, explicitly convertable if self.convertible_from(given_type): return self._dtype(value) diff --git a/tests/metainfo/test_metainfo.py b/tests/metainfo/test_metainfo.py index 5e91c5c765f0c8d0e6ac273a923a7d600ff21c44..5f6e2725418f57afbf15e58b24422a3d3756ac50 100644 --- a/tests/metainfo/test_metainfo.py +++ b/tests/metainfo/test_metainfo.py @@ -675,9 +675,14 @@ class TestM1: test_quantity = Quantity(type=np.dtype('int32')) test_section = TestSection() - test_section.test_quantity = 12 - assert test_section.test_quantity == 12 - assert type(test_section.test_quantity) is np.int32 + + for value in [12, np.array([12], dtype=np.int32)]: + test_section.test_quantity = value + assert test_section.test_quantity == 12 + assert type(test_section.test_quantity) is np.int32 + + with pytest.raises(ValueError): + test_section.test_quantity = np.array([12, 13], dtype=np.int32) def test_scalar_float(self): class TestSection(MSection):