Skip to content

taipy.gui.State

Accessor to the bound variables from callbacks.

State is used when you need to access the value of variables bound to visual elements (see Binding).
Because each browser connected to the application server may represent and modify any variable at any moment as the result of user interaction, each connection holds its own set of variables along with their values. We call the set of these the application variables the application state, as seen by a given client.

Each callback (see Callbacks) receives a specific instance of the State class, where you can find all the variables bound to visual elements in your application.

Note that State also is a Python Context Manager: In situations where you have several variables to update, it is more clear and more efficient to assign the variable values in a with construct:

def my_callback(state, ...):
  ...
  with state as s:
    s.var1 = value1
    s.var2 = value2
  ...

You cannot set a variable in the context of a lambda function because Python prevents any use of the assignment operator.
You can, however, use the assign() method on the state that the lambda function receives, so you can work around this limitation:

Here is how you could define a button that changes the value of a variable directly in a page expressed using Markdown:

   <|Set variable|button|on_action={lambda s: s.assign("var_name", new_value)}|>
This would be strictly similar to the Markdown line:
   <|Set variable|button|on_action=change_variable|>
with the Python code:
def change_variable(state):
    state.var_name = new_value

assign(name, value)

Assign a value to a state variable.

This should be used only from within a lambda function used as a callback in a visual element.

Parameters:

Name Type Description Default
name str

The variable name to assign to.

required
value Any

The new variable value.

required

Returns:

Name Type Description
Any Any

The previous value of the variable.

broadcast(name, value)

Update a variable on all clients.

All connected clients will receive an update of the variable called name with the provided value, even if it is not shared.

Parameters:

Name Type Description Default
name str

The variable name to update.

required
value Any

The new variable value.

required

get_gui()

Return the Gui instance for this state object.

Returns:

Name Type Description
Gui Gui

The Gui instance for this state object.

refresh(name)

Refresh a state variable.

This allows to re-sync the user interface with a variable value.

Parameters:

Name Type Description Default
name str

The variable name to refresh.

required