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?

7
  • If the depth is fixed, you can combine getattr : ...getattr(getattr(sensor[thermo], "att1", None), "attr2", None)... Commented May 3, 2019 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 : stackoverflow.com/questions/3279082/… Commented May 3, 2019 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. Commented May 4, 2019 at 0:15
  • Possible duplicate of Python Chain getattr as a string Commented May 4, 2019 at 16:09
  • @Bogdan Did you try .imu.linear.x instead of .imu.x? Commented May 5, 2019 at 11:37

1 Answer 1

1

The function reduce of functools can be used:

reduce(getattr, "att1.att2.att3".split('.'), sensor[imu])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.