C3 AI Documentation Home

Implement Python Methods on Types

Language features supported by the C3 AI Type System and therefore the Python SDK are as follows:

  • Inheritance
  • Member Methods
  • Constant Fields
  • Method Overloading
  • Method Overwriting
  • Properties
  • Cached Method Results (memoization of previously returned method results)
  • "Remote" Methods (invoking methods implemented in languages beyond Python)
  • "Local" Methods (invoking methods implemented in Python)

Example Python method declaration on a Type

The following is an example Type definition:

Type
// File "Panda.c3typ"
/**
 * A bear native to South Central China
 */
type Panda {

  /**
   * The size of a given Panda's paw
   */
  pawSize: float

  /**
   * The birthday of a given Panda
   */
  birthday: datetime

  /**
   * A list of the names of the locations where Pandas can be found
   *  @param includeCubs
   *    denotes whether we should include the locations of cubs (Pandas of age < 1 year) 
   */
  locations: function(includeCubs: !boolean): [string] py
}

We describe the data model (Type) for a Panda above. A Panda has fields pawSize and birthday, and a static function locations. This function will be invokable on the Panda type and is implemented in Python. The two fields will be accessible from instances of Panda.

Above, we have declared the Panda Type with the locations function. While this method can be invoked from Java, JavaScript, or Python, you only need to implement the method in Python (as declared). The Python SDK will be available in the scope where you implement the method you declared. Implement this method in a Python file living in the same directory as the c3typ file that declares it and shares the same name (with a different file extension):

Python
# File "Panda.py"

# We declared a static method in the c3typ file; in the C3 Python SDK, static methods are treated as class methods
# https://docs.python.org/3/library/functions.html#classmethod
def locations(cls, includeCubs):
    # The c3 variable is the "handle" to the Python SDK
    # `BabyAnimalLocator` is a C3 Type
    # `getLocationOfBabyAnimals` is a static method on this Type, returning `[string]`
    allLocations = ["South Central China", "South Western China", "The San Diego Zoo"]
    if includeCubs:
        return allLocations
    
    locationsWithCubs = c3.BabyAnimalLocator.getLocationOfPandaCubs()
    locationsWithoutCubs = []
    for location in allLocations:
        if location not in locationsWithCubs:
            locationsWithoutCubs.append(location)
    return locationsWithoutCubs

See also

Was this page helpful?