I have a function (here called analyze_data
) that takes an object and a string as input, and uses the string to "extract" data via getattr
. This works fine when the data are in the "frist" level of attributes (data1
). However, I don't know what I can pass to the function to access the data when they are in a lower level (data2
). Passing a dotted string (as shown below) does not work.
class a:
pass
instance1 = a()
# Create 1st data set
instance1.data1 = [1,2,3]
# Create 2nd data set
instance1.subdata = a()
instance1.subdata.data2 = [4,5,6]
def analyze_data(myvar, dataname):
data = getattr(myvar, dataname)
# Do something with data, e.g.:
print(str(data[0]))
analyze_data(instance1, 'data1')
analyze_data(instance1, 'subdata.data2')
What is the best way to access data2
without changing the existing function analyze_data
too much?