Overview

In the first section on Generative Functions, the fastest way to create them was introduced: using the decorator. However, if you’re working in an Object-Oriented Programming (OOP) environment or need to store state that persists across evaluations of the Generative Function, you can define a one as a class instead.

Creating a class-based Generative Function

To create a class-based Generative Function, subclass GenerativeFunction directly. This approach requires gathering all inputs into one Generative Type and all outputs into another.

You can also override the __init__ method (executed when the Function Server starts), which can be helpful for initializing values or preventing repeated computations.

from generative.core import GenerativeFunction, GenerativeType

class Inputs(GenerativeType):
    length_m: float
    ...

class Outputs(GenerativeType):
    deflection_m: float
    ...

class CantileverPointLoadAnalysis(GenerativeFunction[Inputs, Outputs]):
    def __init__(self) -> None:
        super().__init__()
        self._bar = 1

    def run(self, inputs: Inputs) -> Outputs:
        # Contents of the Generative Function
        my_variable = self._bar
        ...

Here, GenerativeFunction is imported from generative.core, and is subclassed to create the Generative Function. The input and output type are specified as type parameters to GenerativeFunction in square brackets. You don’t need to fully understand this syntax, but you can learn more about Python’s type parameters from the Python guide.

Each GenerativeFunction must have a run method defined, with exactly two arguments. The first argument is self, and the second argument is a Generative Type.

If the init method is overridden, the parent init method must be called using super().__init__(). Any variables assigned in the __init__ method are available in the run method.

Under the hood, Generative Functions created by decorating a Python function are converted into class-based Generative Functions with run methods.

While this doesn’t impact functionality, it may explain occasional behavior or error messages.