Closure as click handler does not work?

Since Radiobutton.get_group_value does not work reliably (RadioButton.get_group_value fails when form is not shown (Bug?)) I wanted to try another solution: using a closure as a click handler to the Radiobutton on_select handler I wanted to store the selected value.

  def button_1_click(self, **event_args):
    options = ['alfa', 'beta', 'gamma']

    content = ColumnPanel()
    selected = 'nothing selected yet'
    
    def select(**e):
      selected = e['sender']
      print('In click handler: ', selected.value)
      
    for c in options:
      rb = RadioButton(text=c, value=c, group_name='mygroup')
      content.add_component(rb)    
      rb.set_event_handler('clicked', select)
    
    if alert(content=content):
      print('You selected: ', selected)
      print('The group value', content.get_components()[0].get_group_value())  # fails

I can see that the click handler is called but the selected value is not set in the enclosing scope. To my knowledge that is just the purpose of a closure. Am I missing something?

I you want to try for yourself:
https://anvil.works/build#clone:IVLCTZT54BTFUB2O=NSKNC2QHXHTFEBL4V47IOJL4

You’ve created two closures here. Both of which have their own local variable selected

You’d want to maybe use
nonlocal selected to avoid locally scoping selected within the select function (but that’s not supported in the client).

So instead - as a workaround - you can find a way to access selected without using assignment within the select function. A dictionary might be a good way to do this.

def button_click(self, **event_args):
  selected = {}

  def select(sender, **e):
    selected['value'] = sender.value
    # selected is not locally scoped 
    # because it is not assigned within this function 

You are right.
The dict workaround works. Thx!