1

I am developing an application with check the status of a bunch of sensors.

The way to get their status is very straightforward:

sensor_name.get_status()

Instead of writing several calls to check all those sensors, I was wondering if I could store all sensor names in a list of strings and let a for do the work for me.

Pretty much like this:

sensors_list = ['sensor_name_1', 'sensor_name_2', 'sensor_name_3']
for sensor in sensors_list:
    #call it :-)

How can I get this done?

0

2 Answers 2

4

How about, instead of keeping the names in the list, you just keep the sensors themselves in the list?

sensors = [sensor_1, sensor_2, sensor3]
for sensor in sensors:
    sensor.get_status()
Sign up to request clarification or add additional context in comments.

1 Comment

You can't always control what format the list comes in.
1

Use locals (I will set sensor_name_1 to the min function just so it is callable):

>>> sensor_name_1 = min  # just an example function
>>> locals()['sensor_name_1']([1,2,3])
1

For your specific example, you would do:

sensors_list = ['sensor_name_1', 'sensor_name_2', 'sensor_name_3']
for sensor in sensors
    locals()[sensor].get_status()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.