unpack_fields
unpack_fields
This decorator works on a function that outputs a tuple and unpacks its elements to make them individually available for consumption. Essentially, it expands the original function into n separate functions, each of which takes the original output tuple and, in return, outputs a specific field based on the index supplied to the unpack_fields decorator.
import pandas as pd
from hamilton.function_modifiers import unpack_fields
@unpack_fields('X_train', 'X_test', 'y_train', 'y_test')
def train_test_split_func(
feature_matrix: np.ndarray,
target: np.ndarray,
test_size_fraction: float,
shuffle_train_test_split: bool,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
... # Calculate the train-test split
return X_train, X_test, y_train, y_testThe arguments to the decorator not only represent the names of the resulting fields but also determine their position in the output tuple. This means you can choose to unpack a subset of the fields or declare an indeterminate number of fields — as long as the number of requested fields does not exceed the number of elements in the output tuple.
import pandas as pd
from hamilton.function_modifiers import unpack_fields
@unpack_fields('X_train', 'X_test', 'y_train', 'y_test')
def train_test_split_func(
feature_matrix: np.ndarray,
target: np.ndarray,
test_size_fraction: float,
shuffle_train_test_split: bool,
) -> Tuple[np.ndarray, ...]: # indeterminate number of fields
... # Calculate the train-test split
return X_train, X_test, y_train, y_testReference Documentation
class hamilton.function_modifiers.unpack_fields(*fields: str)[source]
Unpacks fields from a tuple output.
Expands a single function into the following nodes:
- 1 function that outputs the original tuple
- n functions, each of which take in the original tuple and output a specific field
The decorated function must have an return type of either tuple (python 3.9+) or typing.Tuple, and must specify either: - An explicit length tuple (e.g.`tuple[int, str]`, typing.Tuple[int, str]) - An indeterminate length tuple (e.g. tuple[int, …], typing.Tuple[int, …])
Parameters:
fields – Fields to unpack from the return value of the decorated function.
__init__(*fields: str)[source]
Initializes the node transformer to only allow a single node to be transformed. Note this passes target=None to the superclass, which means that it will only apply to the ‘sink’ nodes produced.
评论
登录后参与评论
KnowForge