Introducing Gradio Clients
WatchIntroducing Gradio Clients
WatchWe covered State in Interfaces, this guide takes a look at state in Blocks, which works mostly the same.
Global state in Blocks works the same as in Interface. Any variable created outside a function call is a reference shared between all users.
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:
gr.State()
object. If there is a default value to this stateful object, pass that into the constructor.State
object as an input and output as needed.Let's take a look at a simple example. We have a simple checkout app below where you add items to a cart. You can also check the size of the cart.
import gradio as gr
with gr.Blocks() as demo:
cart = gr.State([])
items_to_add = gr.CheckboxGroup(["Cereal", "Milk", "Orange Juice", "Water"])
def add_items(new_items, previous_cart):
cart = previous_cart + new_items
return cart
gr.Button("Add Items").click(add_items, [items_to_add, cart], cart)
cart_size = gr.Number(label="Cart Size")
gr.Button("Get Cart Size").click(lambda cart: len(cart), cart, cart_size)
demo.launch()
Notice how we do this with state:
gr.State()
object, initialized here to be an empty list.You can think of gr.State
as an invisible Component that can store any kind of value. Here, cart
is not visible in the frontend but is used for calculations.
Learn more about State
in the docs.