0

I am cleaning up some ROS robot code using the method in this QA. This is not ROS related.

Here is the original code:

 data = []
 data.append(sensor[thermo].data.thermo)
 data.append(sensor[imu].data.imu.x)
 data.append(sensor[imu].data.imu.rotation.x)

Now I have a list of tuples containing all the topics so I can loop around:

topics = [('thermo', 'thermo'),
          ('imu', 'imu.x')
          ('imu', 'imu.rotation.x')]

and:

for sensor, topic in topics:
    data.append(getattr[sensor].data, topic)

This works for thermo, but not for imu, and I am getting the following error:

AttributeError: 'imu' object has no attribute 'x'

How can I fix the getattr statement to achieve the goal here?

Bogdan
  • 185
  • 5
  • If the depth is fixed, you can combine `getattr` : `...getattr(getattr(sensor[thermo], "att1", None), "attr2", None)...` – machine424 May 03 '19 at 21:56
  • 3
    Or you can use `reduce` from `functools`: `reduce(getattr, "att1.att2.att3".split('.'), sensor[imu])` I think the question is duplicated : https://stackoverflow.com/questions/3279082/python-chain-getattr-as-a-string – machine424 May 03 '19 at 22:03
  • 1
    @machine424 If you think this question is a duplicate of another post, flag it as such. Also, OP, your Q&A link is broken, so you should update it to the correct URL. – Mihai Chelaru May 04 '19 at 00:15
  • Possible duplicate of [Python Chain getattr as a string](https://stackoverflow.com/questions/3279082/python-chain-getattr-as-a-string) – machine424 May 04 '19 at 16:09
  • @Bogdan Did you try `.imu.linear.x` instead of `.imu.x`? – Benyamin Jafari May 05 '19 at 11:37
  • @BenyaminJafari This is not a ROS related issue. The sensor data path is what it is here. – Bogdan May 06 '19 at 13:32
  • @machine424, I did not know there is a function that handles this. This can be considered as duplicate but I think it is a good example on `reduce` function's application example here and useful to others when they search for this solution. Would you put it in the answer? – Bogdan May 06 '19 at 14:20

1 Answers1

1

The function reduce of functools can be used:

reduce(getattr, "att1.att2.att3".split('.'), sensor[imu])
machine424
  • 155
  • 2
  • 9