* fixup site * fix docs versions * test ci * test ci some more * test ci some more * test ci some more * asd * asd * asd * asd * asd * asd * asd * asd * asd * test * fix * add changeset * fix * fix * fix * test ci * test ci * test ci * test ci * test ci * test ci * test ci * test ci * test ci * notebook ci * notebook ci * more ci * more ci * update changeset * update changeset * update changeset * fix site * fix * fix * fix * fix * fix ci * render mising pages * remove changeset * fix path * fix workflows * fix workflows * fix workflows * fix comment * tweaks * tweaks --------- Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
1.6 KiB
State in Blocks
We covered State in Interfaces, this guide takes a look at state in Blocks, which works mostly the same.
Global State
Global state in Blocks works the same as in Interface. Any variable created outside a function call is a reference shared between all users.
Session State
Gradio supports session state, where data persists across multiple submits within a page session, in Blocks apps as well. To reiterate, session data is not shared between different users of your model. To store data in a session state, you need to do three things:
- Create a
gr.State()
object. If there is a default value to this stateful object, pass that into the constructor. - In the event listener, put the
State
object as an input and output. - In the event listener function, add the variable to the input parameters and the return value.
Let's take a look at a game of hangman.
$code_hangman $demo_hangman
Let's see how we do each of the 3 steps listed above in this game:
- We store the used letters in
used_letters_var
. In the constructor ofState
, we set the initial value of this to[]
, an empty list. - In
btn.click()
, we have a reference toused_letters_var
in both the inputs and outputs. - In
guess_letter
, we pass the value of thisState
toused_letters
, and then return an updated value of thisState
in the return statement.
With more complex apps, you will likely have many State variables storing session state in a single Blocks app.
Learn more about State
in the docs.