Python_script function

I have a script to setup input_select menus… It works as is but if I want to reuse as a function it does not work… It should be exactly the same thing…

this works:

group_entities = hass.states.get('group.all_switches').attributes['entity_id']
# group_entities = ["switch.switch1","switch.sw2","switch.light1","switch.sonoff2,switch.yellow_room","switch.kmc_a","switch.kmc_b","switch.kmc_c"]
all_switches = []
for e in group_entities:
    if "kmc" in e and ("_a" in e or "_c" in e):
        all_switches.append(e)


service_data = {'entity_id': 'input_select.box_1',
                'options': all_switches}
hass.services.call('input_select', 'set_options', service_data)


service_data = {'entity_id': 'input_select.box_2',
                'options': all_switches}
hass.services.call('input_select', 'set_options', service_data)

but if I put it into a function then nothing happens…

def update_data(entity):
    service_data = {'entity_id': 'input_select.'+entity,
                    'options': all_switches}
    hass.services.call('input_select', 'set_options', service_data)


update_data('box_1')
update_data('box_2')

they both print() (if tried in python console without the hass.service.call()):

{'entity_id': 'input_select.box_1', 'options': ['switch.kmc_a', 'switch.kmc_c']}
{'entity_id': 'input_select.box_2', 'options': ['switch.kmc_a', 'switch.kmc_c']}

i know very little python, but don’t you need to return something in the function?

https://www.programiz.com/python-programming/function

I also know very little but in the link you posted it says:

  1. An optional return statement to return a value from the function.

I don’t think a return is required.

Anything in the logs?

Python scripts are run within RestrictedPython so running the script in the console isn’t proof the script is working within that environment.

I’m no expert but I’m wondering if it might be a scoping issue.

Perhaps pass the all_switches variable into the function?

You have to pass the hass object as a parameter to the function.

def update_data(hass, entity):

you can just do another for loop instead of a function. Typically functions in python scripts are very limited because the environment is limited. It’s not like normal python.

group_entities = hass.states.get('group.all_switches').attributes['entity_id']
# group_entities = ["switch.switch1","switch.sw2","switch.light1","switch.sonoff2,switch.yellow_room","switch.kmc_a","switch.kmc_b","switch.kmc_c"]
all_switches = []
for e in group_entities:
    if "kmc" in e and ("_a" in e or "_c" in e):
        all_switches.append(e)

service_data =  {'options': all_switches}
for n in ['box_1', 'box_2']:
    service_data['entity_id'] = 'input_select.{}'.format(n)
    hass.services.call('input_select', 'set_options', service_data)