Skip to content

treex.Compact

first_run: bool property readonly

Returns:

Type Description
bool

True if its currently the first run of a compact method.

get_field(self, field_name, initializer)

A method that gets a field with the given name if exists, otherwise it initializes it and returns it.

Currently the follow restrictions apply:

  • The field must be declared in the class definition.
  • The method can only be called inside a compact context.

Parameters:

Name Type Description Default
field_name str

The name of the field to get.

required
initializer Callable[[], ~A]

The function to initialize the field if it does not exist.

required

Returns:

Type Description
~A

The field value.

Source code in treeo/mixins.py
def get_field(
    self,
    field_name: str,
    initializer: tp.Callable[[], A],
) -> A:
    """
    A method that gets a field with the given name if exists, otherwise it initializes it and returns it.

    Currently the follow restrictions apply:

    * The field must be declared in the class definition.
    * The method can only be called inside a `compact` context.

    Arguments:
        field_name: The name of the field to get.
        initializer: The function to initialize the field if it does not exist.

    Returns:
        The field value.
    """
    value: A

    if field_name not in self._field_metadata:
        raise ValueError(f"Metadata for field '{field_name}' does not exist.")

    if field_name in vars(self):
        value = getattr(self, field_name)
    else:
        if tree_m._COMPACT_CONTEXT.in_compact and not self.first_run:
            raise RuntimeError(
                f"Trying to initialize field '{field_name}' after the first run of `compact`."
            )

        value = initializer()
        setattr(self, field_name, value)

    return value