Repository navigation
Add to_quantity and from_quantity #2468
Description
Activity
There is also
1 * sc.Unit(None)which fails withTypeError: __init__(): incompatible constructor arguments. The following argument types are supported: 1. scipp._scipp.core.Unit(arg0: str) Invoked with: NoneMaybe that should be allowed?
This comes from the constructor of
Unit. And I don't think this should be allowed. Because we store the unit as eitherUnitor None.This comes from the constructor of
Unit. And I don't think this should be allowed. Because we store the unit as eitherUnitor None.Agree.
I also don't think we should support this in
to_unit. Is there an example where this is useful? Maybe it can be fixed in a better manner "upstream" in the code?I ran into this in a case where code constructed a mask using arithmetic and used
da.masks['mask'] = to_unit(x, dtype=bool). Right now, we need to useda.masks['mask'].unit = Nonein a separate line. It would be nice to combine the unit and dtype 'conversion' in a singleto-call. But it is not super relevant.Like I said, my main problem with the current behaviour is that
tosilently does nothing when passedunit=None.We should consider dedicated functions to do these kinds of conversions. Basically, everything with a unit is a quantity, so I would suggest
sc.to_quantity(var, unit). Not sure about the reverse, could besc.from_quantity(var)?- changed the title
[-]unit=None in to and to_unit[/-][+]Add `to_quantity` and `from_quantity`[/+]on May 6, 2022 - addedenhancementNew feature or requestNew feature or request
on May 6, 2022 We could also do it in the spirit of
np.asarray:x = sc.asquantity(y, unit='m')
which would either (1) ensure that
yhas unit 'm', or (2) ify.unit is None, as the unit. This would allow for expressing contracts or expectations about a function's inputs, for example
Do we want to support these?
They currently don't work.
to_unitraises an exception buttodoes nothing becauseNoneis used to mean 'do not change'.I am leaning towards not supporting this because those functions are meant for converting between compatible units. So one should use
var.unit = Noneinstead.However, if we decide to not support it,
toneeds to handle that case and also raise an exception.EDIT
What about the other way around?