check_units
- plasmapy.utils.decorators.checks.check_units( )[source]
A decorator to ‘check’ — limit/control — the units of input and return arguments to a function or method.
- Parameters:
func – The function to be decorated
checks_on_return (list of
unitsor dict of unit specifications) – Specifications for unit checks on the return of the function being wrapped. (see “check units”_ for valid specifications)**checks (list of
unitsor dict of unit specifications) –Specifications for unit checks on the input arguments of the function being wrapped. Each keyword argument in
checksis the name of a function argument to be checked and the keyword value contains the unit check specifications.Unit checks can be defined by passing one of the astropy
units, a list of astropy units, or a dictionary containing the keys defined below. Units can also be defined with function annotations, but must be consistent with decorator**checksarguments if used concurrently. If a key is omitted, then the default value will be assumed.Key
Type
Description
units
list of desired astropy
unitsequivalencies
[DEFAULTNone] A list of equivalent pairs to try ifthe units are not directly convertible.pass_equivalent_units
[DEFAULTFalse] allow equivalent unitsto pass
Notes
Checking of function arguments
*argsand**kwargsis not supported.Decorator does NOT perform any unit conversions, look to
validate_quantities()if that functionality is desired.If it is desired that
Nonevalues do not raise errors or warnings, then includeNonein the list of units or as a default value for the function argument.If units are not specified in
checks, then the decorator will attempt to identify desired units by examining the function annotations.Full functionality is defined by the class
CheckUnits.
Examples
Define units with decorator parameters:
import astropy.units as u from plasmapy.utils.decorators import check_units @check_units(arg1={"units": u.cm}, arg2=u.cm, checks_on_return=[u.cm, u.km]) def foo(arg1, arg2): return arg1 + arg2 # or on a method class Foo: @check_units(arg1={"units": u.cm}, arg2=u.cm, checks_on_return=[u.cm, u.km]) def bar(self, arg1, arg2): return arg1 + arg2
Define units with function annotations:
@check_units def foo(arg1: u.cm, arg2: u.cm) -> u.cm: return arg1 + arg2 # or on a method class Foo: @check_units def bar(self, arg1: u.cm, arg2: u.cm) -> u.cm: return arg1 + arg2
Allow
Nonevalues to pass:@check_units(checks_on_return=[u.cm, None]) def foo(arg1: u.cm = None): return arg1
Allow return values to have equivalent units:
@check_units( arg1={"units": u.cm}, checks_on_return={"units": u.km, "pass_equivalent_units": True}, ) def foo(arg1): return arg1
Allow equivalent units to pass with specified equivalencies:
@check_units( arg1={ "units": u.K, "equivalencies": u.temperature(), "pass_equivalent_units": True, } ) def foo(arg1): return arg1