Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to determine if a quantity is a scalar or a list #1271

Closed
edmundsj opened this issue Mar 23, 2021 · 2 comments
Closed

How to determine if a quantity is a scalar or a list #1271

edmundsj opened this issue Mar 23, 2021 · 2 comments

Comments

@edmundsj
Copy link

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.

@edmundsj
Copy link
Author

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")

@hgrecco
Copy link
Owner

hgrecco commented Mar 23, 2021

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

@hgrecco hgrecco closed this as completed Mar 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants