Helper functions (Variable helpers)¶
As shown in the previous chapter, documents can contain variables and call
helper functions, so called “variable helpers”. You can define your own helpers,
by adding methods to your document and adding the variable_helper()
decorator to them.
Inside the variable helper method you can access all fields of your document, as well as all other
methods and variable helpers. All documents have a helper method called parent()
that returns the parent document.
from schema import Schema, SchemaError, Optional
from configcrunch import YamlConfigDocument, variable_helper
class Example(YamlConfigDocument):
@classmethod
def header(cls) -> str:
return "example"
@classmethod
def schema(cls) -> Schema:
return Schema({
'this': str,
'int': int
})
@classmethod
def subdocuments(cls):
return []
@variable_helper
def my_helper(self, param):
# Since variable helpers are called while the document isn't frozen yet,
# you need to use the internal_... methods to get data from the document,
# see the "Accessing Data" section.
return self.internal_get('int') + param
Example usage:
example:
this: '{{ my_helper(3) }}'
int: 5
This will result in the following document:
example:
this: 8
int: 5