patch_function

function of dascore.utils.patch source

patch_function(
    required_dims: tuple[tuple[str, …], Callable, None] = None,
    required_coords: tuple[tuple[str, …], None] = None,
    required_attrs: dict[dict[str, Any], str, collections.abc.Sequence[str], None] = None,
    history: Literal[‘full’, ‘method_name’, None] = full,
    validate_call: bool = False,
)

Decorator to mark a function as a patch method.

Parameters

Parameter Description
required_dims A tuple of dimensions which must be found in the Patch.
required_coords A tuple of coordinates which must be found in the Patch.
required_attrs A dict of attributes which must be found in the Patch and whose
values must be equal to those provided.
history Specifies how to track history on Patch.
Full - Records function name and str version of input arguments.
method_name - Only records method name. Useful if args are long.
None - Function call is not recorded in history attribute.
validate_call If True, use pydantic to validate the function call. This can save
quite a lot of code in validation checks, but does have some overhead.
See validate_call.

Examples

import dascore as dc

# 1. A patch method which requires dimensions (time, distance)
@dc.patch_function(required_dims=('time', 'distance'))
def do_something(patch):
    ...   # raises a PatchCoordsError if patch doesn't have time,
    #  distance

# 2. A patch method which requires an attribute 'data_type' == 'DAS'
@dc.patch_function(required_attrs={'data_type': 'DAS'})
def do_another_thing(patch):
    ...  # raise PatchAttributeError if patch doesn't have attribute
    # called "data_type" or its values is not equal to "DAS".

# 3. A patch method which does type checking on inputs.
# The `Field` instance can require various data properties (like ranges)
from typing_extensions import Annotated, Literal
from pydantic import Field
@dc.patch_function(validate_call=True)
def do_type_thing(
    patch,
    int_le_10_ge_1: int = Field(ge=1, le=10, default=1),
    option: Literal["min", "max", None] = None,
):
    ...
Note
  • The original function can still be accessed with the raw_function attribute. This may be useful for avoiding calling the patch_func machinery multiple times from within another patch function.

  • If using PatchType or SpoolType type variables from the constants module, make sure dascore is imported as dc at the top of the file where the patch function is defined so the forward refs can be resolved properly for type checking.