Dewster35 wrote:I guess I don't quite follow. Why are we doing two lists and how would those lists differ?
In my approach, we maintain two lists because we're tracking two different device states (actually more than two state
values) that contain different value types. The first list --company_devices_1 -- will hold the current state of all devices that support the onOffState (True or False). We evaluate that list later to see if any of the states that we've collected are True (the device is on). If yes, we set the variable to on. The second list -- company_devices_2 -- will hold the current state of all devices that support the 'status' state (Up or Down or Expired). We evaluate that list later to see if any of the states that we've collected are Up. If yes, we set the variable to on.
When we evaluate the first list we've created, we search it to see if any of its values are True. When we evaluate the second list we've created, we search it to see if any of its values are Up. We need a separate list because in Python Up/Down/Expired will all evaluate to True if we examine their 'truthiness', so if we added them to the first list, our result would always be True (you would always have company).
Also, why are we checking onoffstate if the device does not contain that?
In my approach, we're first seeing if a device contains the state 'onOffState'. We do this by trying to add the device's onOffState to our list. If the device doesn't contain that state, our attempt will fail and "throw an exception." We ignore the exception and move on to trying to evaluate our next state 'status'. If our device doesn't support either of those two states (fails both tests) we skip it and move on to the next device. If a device somehow supports both the 'onOffState' and 'status' states, it will be evaluated for both. You can think about the try/except bock as meaning "If device x supports the onOffState, then do something". There are other ways that we could do this. For example, instead of the try/except test, we could also do this:
- Code: Select all
if 'onOffState' in dev.states:
# do something
Which is more human-friendly on the face; however, in my opinion, it's less optimal because we have to search every state of every device we evaluate to see if it passes the test. With the try/except block, we cut right to the chase and if the test fails (we've only effectively evaluated one state per device) we move on to the second test.