4.5. Saving and Loading
Saving
Let us create a simple transition that counts how many times the user visits:
#4
: calls the macro#VISITS
defined in#7
.
MacroVisits
can be defined as follow:
#10-13
: uses the match statements to return the appropriate literal.
The challenge is that we must save the number of visits to make this macro effective (and correct). This can be achieved by saving the variable dictionary into a binary file using the built-in Python object serialization called pickle:
#1
: takes a dialogue flowdf
and a file pathvarfile
for saving the variable dictionary to.#3
: creates a dictionary by copying only user-generated variables.#4
: opens a writable (w
) and binary (b
) file and dumps the dictionry object into the file.
After running this code, you will see the visits.pkl
file saved under the resources
directory.
Loading
The following code shows how to load the saved dictionary to a new dialogue flow:
#1
: takes a dialogue flowdf
and a file pathvarfile
for loading the variable dictionary from.#2
: opens a readable (r
) and binary (b
) file and loads the object as a dictionary.#3
: adds all variables in the loaded dictioinary to the variable dictionary ofdf
.#5
: saves the new variable dictionary to the same file.
Last updated