Decorators

marine_qc.auxiliary.generic_decorator(pre_handler=None, post_handler=None)[source]

Create a decorator that binds function arguments and applies pre- and post-processing handlers.

This decorator factory allows you to inspect, modify, or validate function arguments before and after the original function is called. Reserved keyword arguments can be passed to the handlers via _decorator_kwargs and removed from the call to the original function.

Parameters:
  • pre_handler (Callable[[dict], None]) – A function that takes the bound arguments dictionary (bound_args.arguments) and optionally additional keyword arguments, to inspect or modify arguments before the decorated function executes. Signature: handler(arguments: dict, **meta_kwargs) -> None.

  • post_handler (Callable[[dict], None]) – A function that takes the bound arguments dictionary (bound_args.arguments) and optionally additional keyword arguments, to inspect or modify arguments after the decorated function executes. Signature: handler(arguments: dict, **meta_kwargs) -> None.

Return type:

Callable[..., Any]

Returns:

Callable – A decorator that wraps any function. When applied, the function’s arguments are bound and passed to the handlers before execution.

Notes

  • Handlers can define a _decorator_kwargs attribute (a set of reserved keyword argument names). These reserved kwargs will be extracted from the decorated function’s call kwargs, passed to the handler, and removed before calling the original function.

  • The original function is called with the possibly modified bound arguments after handler processing.

marine_qc.auxiliary.convert_units(**units_by_name)[source]

Decorator to automatically convert specified function arguments to target units.

This decorator allows a function to accept inputs in various units and automatically converts them to desired target units before the function executes. It is especially useful for scientific or engineering functions where users may provide inputs in different unit systems.

Parameters:

**units_by_name (str) – Keyword arguments mapping function argument names to their target units. Special case: if a target unit is “unknown”, it will be converted to the base SI unit for the given source unit (e.g., “degC” ? “K”, “km/h” ? “m/s”).

Return type:

Callable[..., Any]

Returns:

Callable[..., Any] – A decorator that converts specified parameters to the target units prior to executing the decorated function.

Notes

  • The decorated function must be called with a units keyword argument, which can be:
    • A dictionary mapping argument names to their source units, or

    • A single string unit applied to all arguments.

  • Parameters not listed in units_by_name are not converted.

  • Parameters with None values are skipped.

  • If a target unit is “unknown”, the value is converted to the base SI unit.

Examples

>>> @convert_units(temperature="K")
... def func_single(temperature):
...     print(f"Temperature: {temperature:.2f} K")
>>> func_single(25.0, units={"temperature": "degC"})
Temperature: 298.15 K
>>> @convert_units(speed="m/s", altitude="m")
... def func_multiple(speed, altitude):
...     print(f"Speed: {speed:.1f} m/s, Altitude: {altitude:.0f} m")
>>> func_multiple(72.0, 0.5, units={"speed": "km/h", "altitude": "km"})
Speed: 20.0 m/s, Altitude: 500 m
>>> @convert_units(distance="unknown")
... def func_base(distance):
...     print(f"Distance in SI units: {distance} m")
>>> func_base(1.2, units={"distance": "km"})
Distance in SI units: 1200.0 m
marine_qc.auxiliary.inspect_arrays(params, sortby=None)[source]

Decorator to convert and validate specified function input parameters as 1D NumPy arrays.

This decorator ensures that specified input arguments are sequence-like, converts them to 1D NumPy arrays, validates that they are one-dimensional, and checks that all arrays have the same length. Optionally, the arrays can be sorted by another parameter and later restored to the original order.

Parameters:
  • params (list of str) – Names of parameters to inspect in the decorated function. Each specified parameter will be converted to a 1D NumPy array and validated.

  • sortby (str, optional) – Name of a parameter to sort the arrays by, if desired. The result will be returned in the original order of this parameter.

Return type:

Callable[..., Any]

Returns:

Callable[..., Any] – A decorator that, when applied, converts the specified parameters to 1D NumPy arrays, validates them, optionally sorts them, and passes them to the decorated function.

Raises:

ValueError – If a specified parameter is missing from the function arguments. If any specified parameter is not one-dimensional. If the lengths of the specified arrays do not all match.

Notes

  • If sortby is specified, the result of the function is reordered to match the original order of sortby after the function executes.

Examples

>>> @inspect_arrays(["a", "b"])
... def add_arrays(a, b):
...     return a + b
>>> add_arrays([1, 2, 3], [4, 5, 6])
array([5, 7, 9])
>>> add_arrays([1, 2], [3, 4, 5])
Traceback (most recent call last):
    ...
ValueError: Input ['a', 'b'] must all have the same length.
marine_qc.auxiliary.post_format_return_type(params, dtype=<class 'int'>, multiple=False)[source]

Decorator to format a function’s return value to match the type of its original input(s).

This decorator ensures that the output of the decorated function is converted back to the same structure/type as the original input(s) specified by params. It uses a context object (_ctx) if available to retrieve the original inputs before any preprocessing was applied. If no context is found, it falls back to the current bound arguments.

Parameters:
  • params (list of str) – List of parameter names whose original input types should be used to format the return value.

  • dtype (type, optional) – Desired data type of the result. Default is int.

  • multiple (bool, optional) – If True, assumes the function returns a sequence of results (e.g., a tuple), and applies format_return_type to each element individually. If False (default), applies format_return_type once on the entire result.

Return type:

Callable[..., Any]

Returns:

Callable[..., Any] – A decorator that modifies the decorated function’s output to match the input types.

Notes

  • Assumes a TypeContext object may be passed via _ctx keyword argument, storing original input values for accurate type formatting.

  • Falls back gracefully if no context is available, using current arguments.

  • Useful when function inputs are preprocessed (e.g., converted to arrays), and the output should match the original input types.

marine_qc.external_clim.inspect_climatology(*climatology_keys, optional=None)[source]

A decorator factory to preprocess function arguments that may be Climatology objects.

This decorator inspects the specified function arguments and normalizes them to concrete numerical values before the decorated function is executed. Supported input types include raw numeric values, xarray objects, file paths, and Climatology instances.

Parameters:
  • *climatology_keys (str) – Names of required function arguments to be inspected. These should be arguments that may be:

    • a numeric value

    • a xr.DataArray

    • a xr.Dataset

    • a string or path-like object pointing to a valid NetCDF file on disk

    • a Climatology instance

    If a Climatology object (or an object convertible to one) is detected, it will be resolved to a concrete value using its .get_value_fast(**kwargs) method.

  • optional (str or sequence of str, optional) – Argument names that should be treated as optional. If they are explicitly passed when the decorated function is called, they will be treated the same way as climatology_keys.

Return type:

Callable[..., Any]

Returns:

Callable[..., Any] – A decorator that wraps the target function, processing specified arguments before the function is called.

Raises:
  • TypeError – If a required climatology argument is missing from the decorated function call

  • ValueError – If an xr.Dataset is provided without specifying clim_name, or if a string/Path input does not point to a valid file on disk.

Warns:

UserWarning – Issued if required keyword arguments for get_value_fast() are missing. This warning does not stop execution; missing values are replaced with np.nan.

Notes

  • xr.Dataset inputs require the keyword argument clim_name to select the relevant data variable.

  • xr.DataArray inputs are automatically wrapped in a Climatology object.

  • String or path-like inputs must point to an existing file and are opened via open_netcdf_file().

  • If a Climatology object is processed, it is resolved using .get_value_fast(**kwargs).

  • If required keyword arguments for .get_value_fast() are missing, a warning is issued.

  • If resolution fails due to TypeError or ValueError, the value is replaced with np.nan.

marine_qc.time_control.convert_date(params)[source]

Decorator to extract date components and inject them as function parameters.

This decorator intercepts the ‘date’ argument from the function call, splits it into its components (e.g., year, month, day), and assigns those components to specified parameters in the wrapped function. It supports scalar or sequence inputs for ‘date’.

Parameters:

params (list of str) – List of parameter names corresponding to date components to be extracted and passed to the decorated function.

Return type:

Callable[..., Any]

Returns:

Callable[..., Any] – A decorator that wraps a function, extracting date components before calling it.

Notes

  • The decorator expects the wrapped function to accept the parameters listed in params. If a parameter is missing, it raises a ValueError.

  • If the ‘date’ argument is None, the original function is called without modification.

  • Supports scalar-like ‘date’ values as well as iterable sequences.

  • Assumes a helper function split_date exists that splits a date into components and returns a dictionary mapping parameter names to their values.