You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
So I am trying to check if a quantity is a scalar or a list, and in each case, I want to treat them differently. However, they appear to have the same type (pint.Quantity), which makes this impossible without a try/except block. Normally I would do something like isinstance(quantity, quantity_array). Even scalar-valued quantities have the len method implemented, so I can't use this as a check. Is there an easier way than this (below)?
import pint
ureg = pint.UnitRegistry()
qt = 1.0 * ureg.mV
try:
len(qt)
print("This is a list")
except:
print("This is a scalar")
It seems awkward and like there should be an easier way.
The text was updated successfully, but these errors were encountered:
It looks like the magnitude of the quantity retains its original type, so my solution is the following:
import pint
ureg = pint.UnitRegistry()
qt = 1.0 * ureg.mV
if isinstance(qt.magnitude, (list, np.ndarray)):
print("This is a list")
else:
print("This is a scalar")
This is still a little awkward, because I have to do two checks: first if the object is a quantity, and then if its magnitude is a list (instead of just checking if the object is a list of quantities, whatever that type may be). My objects could be vanilla lists, in which case they won't have a magnitude and the code above will throw an error. It would be nice to do something like:
import pint
ureg = pint.UnitRegistry()
qt = 1.0 * ureg.mV
if isinstance(qt pint.QuantityArray):
print("This is a list")
else:
print("This is a scalar")
Pint (currently) wraps (not subclass) numerical classes. But there is long standing discussion if we should move to subclassing numpy.ndarray or makeing two subclass QuantityScalar/QuantityArray. See #1128 and similars
So I am trying to check if a quantity is a scalar or a list, and in each case, I want to treat them differently. However, they appear to have the same type (
pint.Quantity
), which makes this impossible without a try/except block. Normally I would do something like isinstance(quantity, quantity_array). Even scalar-valued quantities have the len method implemented, so I can't use this as a check. Is there an easier way than this (below)?It seems awkward and like there should be an easier way.
The text was updated successfully, but these errors were encountered: