check_quantity

plasmapy.utils.checks.check_quantity(**validations)

Verify that the function’s arguments have correct units.

This decorator raises an exception if an annotated argument in the decorated function is an Quantity with incorrect units or of incorrect kind. You can prevent arguments from being input as Nones, NaNs, negatives, infinities and complex numbers.

If a number (non-Quantity) value is inserted in place of a value with units, assume the input is an SI Quantity and cast it to one.

This is probably best illustrated with an example:

Examples

>>> from astropy import units as u
>>> @check_quantity(x={"units": u.m,
...       "can_be_negative": False,
...       "can_be_complex": True,
...       "can_be_inf": True})
... def func(x):
...     return x
>>> func(1 * u.m)
<Quantity 1. m>
>>> func(1 * u.s)
Traceback (most recent call last):
  ...
astropy.units.core.UnitConversionError: The argument x to func should be a Quantity with the following units: m
>>> import pytest    # to show the UnitsWarning
>>> with pytest.warns(u.UnitsWarning, message="Assuming units of m."):
...     func(1)
<Quantity 1. m>
>>> func(-1 * u.m)
Traceback (most recent call last):
  ...
ValueError: The argument x to function func cannot contain negative numbers.
>>> func(np.inf * u.m)
<Quantity inf m>
>>> func(None)
Traceback (most recent call last):
  ...
ValueError: The argument x to function func cannot contain Nones.
Parameters:

dict – Arguments to be validated passed in as keyword arguments, with values as validation dictionaries, with structure as in the example. Valid keys for each argument are: ‘units’: astropy.units.Unit, ‘can_be_negative’: bool, ‘can_be_complex’: bool, ‘can_be_inf’: bool, ‘can_be_nan’: bool, ‘none_shall_pass’: bool

Raises:
  • TypeError – If the argument is not a Quantity, units is not entirely units or argname does not have a type annotation.
  • UnitConversionError – If the argument is not in acceptable units.
  • UnitsError – If after the assumption checks, the argument is still not in acceptable units.
  • ValueError – If the argument contains nan or other invalid values as determined by the keywords.
Warns:

`~astropy.units.UnitsWarning` – If a Quantity is not provided and unique units are provided, a UnitsWarning will be raised and the inputted units will be assumed.

Notes

This functionality may end up becoming deprecated due to noncompliance with the IEEE 754 standard and in favor of quantity_input.

Returns:Decorated function.
Return type:function