Concept Summary: Using Variables in a Code Recipe¶
In Variables 101 we discussed how project variables are used in visual recipes. In this lesson, we will learn how project variables are used in code recipes by looking at two types of code recipes: Python and SQL.
Code Recipe: Python¶
When we define variables and use them within a Python recipe, we are interacting with the Python APIs in Dataiku DSS. More specifically, we are using the Python API package, dataiku.
This package is automatically included in Python notebooks and code recipes. When working with a scenario, we can manually import the package.
All of our variables, including global and project variables, are stored in a Python dictionary. In our example, the global project variables are merch_state and merch_category.
To retrieve our variables from the Python dictionary, we use the “get custom variables” function. As a result, Dataiku DSS returns our project variables, our project key, and the path to our data directory.
Because DSS stores the variables in a dictionary, we can use any of the dictionary’s keys with the Get Custom Variables function to easily retrieve its corresponding value. For example, using the function with the merch_state key returns the value ‘Arizona’ from the dictionary.
If we want to retrieve a dictionary that contains the dictionary keys for our global and local project variables, we can do so by using our unique project key.
This returns a dictionary with two keys ‘standard’ and ‘local,’ where standard represents our global project variables. and ‘local’ represents the local project variables.
This code snippet might seem a bit lengthy but it is useful for updating the value of our project variables.
Code Recipe: SQL¶
Now let’s look at how variables are used in the code of an SQL recipe.
To use a variable in the code of our SQL recipe, we use a specific syntax, where we start with a dollar sign and wrap the name of our variable in curly brackets.
For example, this query will return all rows from our logs file where the column name is not equal to the value of our variable.