Skip to content
Snippets Groups Projects
Commit 505bb2d7 authored by Theodore Chang's avatar Theodore Chang
Browse files

Merge branch 'metainfo-ensure-scalar' into 'develop'

Metainfo ensure scalar input

See merge request !2173
parents fb66c2a6 2afa240c
No related branches found
No related tags found
1 merge request!2173Metainfo ensure scalar input
Pipeline #224275 passed
......@@ -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)
......
......@@ -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):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment