Page scoping and variables in Taipy

70 Views Asked by At

I have a structure of three separate pages called from main. Does each page have its own state variable or does the architecture create a single state variable that I can call from any of the pages? If they are separated, how do I call the states between pages?

Code organisation

I expect to use other variables from other pages, but I get an error message saying that other variables from other pages are not accessible.

1

There are 1 best solutions below

0
Florian Jacta On BEST ANSWER

Did you use the Markdown object of Taipy? If you don't use it, you should put all your variables in your main script to access it.

from ... import xxx, yyy

The variables and callbacks are scoped to your page if you use the Markdown object. It means you cannot access variables scoped on one page on another page. If they are common variables, you should have them in your main script. However, you can always access them with:

state['your-page'].variable_name

Here is some documentation on variable binding.

For example, you can look at this code from the Covid Dashboard demo. I am importing only the Markdown objects and the other necessary variables present on multiple pages.

from taipy.gui import Gui
import taipy as tp

from pages.country.country import country_md
from pages.world.world import world_md
from pages.map.map import map_md
from pages.predictions.predictions import predictions_md, selected_scenario
from pages.root import root, selected_country, selector_country

from config.config import Config

pages = {
    '/':root,
    "Country":country_md,
    "World":world_md,
    "Map":map_md,
    "Predictions":predictions_md
}


gui_multi_pages = Gui(pages=pages)

if __name__ == '__main__':
    tp.Core().run()
    
    gui_multi_pages.run(title="Covid Dashboard")

And here (last row of on_change_params) I am using a callback function to update another page (Country page).

def on_change_params(state):
    if state.selected_date.year < 2020 or state.selected_date.year > 2021:
        notify(state, "error", "Invalid date! Must be between 2020 and 2021")
        state.selected_date = dt.datetime(2020,10,1)
        return
    
    state.selected_scenario.date.write(state.selected_date.replace(tzinfo=None))
    state.selected_scenario.country.write(state.selected_country)
    notify(state, "success", "Scenario parameters changed!")

    state['Country'].on_change_country(state)