'Is there an alternative for Python's eval when trying to retrieve nested attributes?

I am given a config, with one part containing multiple paths and expressions to attributes of a class. I have to retrieve the required attributes given the paths as strings in Python 3. As an example, a config may look like this:

...
class_foo:
   attr_x: foo.class_bar.attr_x
   attr_y: foo.dict_x['xy'].toList()
   attr_z: foo.list_x[0]
...

These paths could be more or less complex expressions to retrieve any attribute in nested classes. I am currently evaluating them using the eval() statement. To reduce security risk, I tried to cut the foo. from the input string and add it separately again, such that most other unwanted statements in a different format would fail.

def get_attr(foo, statement):
   return eval('foo.' + statement)

I am quite sure that this is not enough to prevent possible security risks, but I have not found any alternative which is not way to complex. I already tried using the reduce function in combination with getattr, but this then fails when a dictor listhas to be evaluated.

Is this usecase a valid reason to use eval()? Is there any alternative I am missing? What can be done to make the use of eval() here more safe?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source