Reference variable from another function?

What I’m trying to do:

I have a function which takes an argument from a form, packages it into a SQL query to an external database, and returns some data in a variable called “res_list” which is then populated into a DataGrid.

Now, I want to give users an option to download the entire response as an excel spreadsheet.

What I’ve tried and what’s not working:

I have the following code which generates the variable:

class Form1(Form1Template):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)

    # Any code you write here will run before the form opens.

  def submit_btn_click(self, **event_args):
    criteria = self.criteria_dropdown.selected_value
    print(criteria)
    kwd = self.kw_input.text
    print(kwd)
    res_list = anvil.server.call('run_sql',criteria,kwd)
    self.repeating_panel_1.items = res_list

And I added the following client side code (as well as server side code) which references the same “res_list” variable.

def all_data_download_click(self, **event_args):
      result = anvil.server.call("export_to_excel", res_list)
      anvil.media.download(result)

However, when I run the entire program, I get an error: “NameError: name ‘res_list’ is not defined”. Please note that both functions are within the same class in the client side.

I appreciate any suggestions

In Python, variables declared inside a function are only available in that function. The Anvil way to allow what you’re trying to do is to make the variable part of the form, instead of the function, by adding self. in front of it. e.g.

    self.res_list = anvil.server.call('run_sql',criteria,kwd)
    self.repeating_panel_1.items = self.res_list

and

result = anvil.server.call("export_to_excel", self.res_list)
3 Likes

If you want to know more about why @jshaffstall 's answer is the correct one, what he is referring to is called scope, and the python scope rules are pretty simple. (especially due to how indentation works)

Here is just one reference found by googling “python scope rules”:

2 Likes