Variables 101: Variables for Coders

In the course, Variables 101, you learned how to use variables, in visual recipes, throughout the Flow. Variables can also be defined, called, and updated through code, such as in a code-based recipe, or an application.

Defining Variables

All variables are defined as a JSON object. When naming variables, you should follow a convention that uses a descriptive noun and includes only alphanumeric characters or the underscore character.

You define project variables by selecting > Variables from the top navigation bar in Dataiku DSS and typing the applicable JSON code.

../../../../_images/variables-defined.png

Once you have defined project variables, you can document them in the project’s Wiki for others who use your project.

To find out more about defining variables, visit the Dataiku DSS Reference Documentation.

Using Variables in the Code of a Code Recipe

The code syntax you use to call variables depends on the code language used in a recipe.

You can call variables by using code from notebooks or code recipes. For example, the following code in a Python Recipe calls a variable “your_variable_name”:

import dataiku
dataiku.get_custom_variables()["your_variable_name"]

Similarly, the following code in an SQL Recipe calls a variable “your_variable_name”:

where "column" =
'${your_variable_name}'

You can also update the value of a variable via code in a code-based recipe. For example, the following code in a Python Recipe updates the value of a variable “your_variable_name” in a dictionary:

import dataiku
p = dataiku.Project() # you have to load your Dataiku project first
variables = p.get_variables() # you retrieve your variables
variables["standard"]["your_variable_name"] = "your_variable_value" # you manipulate the dictionary to update the variable you want
p.set_variables(variables) # you set the updated dictionary

As you can see, when calling and updating a variable via code, such as in a code recipe, the core objective is the same as when calling a variable using a visual recipe.

Using code, you can leverage your variables in coding recipes and Webapps. You can leverage scenarios to automate the variable update process. For example, you can combine scenarios with applications to update the project variables based on user input, or external parameters such as dates.

What’s Next

Now you can try building a more advanced application that uses a customer ID variable in the Dataiku Applications Tutorials lesson: Create a Visual Application.