I have been using nested arrays parsed from a json. This ends up giving a gigantic line each time I try to access values in the data. let's say I have a nested array in the var data, when I try to reach the deeper values, I still have to respect the 80 characters limit. All I want to do is read or modify the value.
self.data["name1"]["name2"][varWithNumber][varWithNumber2][varWithNumber3]
Now, I thought about two possible solutions I could use:
1- split it using temporary vars and then reasign it to the data once I am done ex:
tempData=self.data["name1"]["name2"][varWithNumber]
tempData[varWithNumber2][varWithNumber3]+=1
self.data["name1"]["name2"][varWithNumber]=tempData
I guess this solution would use quite a bit of ressources from all the memory copied around.
2- use the exec function implemented in python and split the string on multiple lines:
exec ('self.data'+
'["name1"]'+
'["name2"]'+
'[varWithNumber]'+
'[varWithNumber2]'+
'[varWithNumber3]+=1')
I have no idea how optimised is the exec function. What would be the most pythonic/optimised way to do this? Is there any other/better way to reach the goal whilst respecting the pep8?
(Bit long for a comment) You don't need exec to do that... you can use the line continuation operator:
self.data["name1"]\
["name2"]\
[varWithNumber]\
[varWithNumber2]\
[varWithNumber3]
Demo:
In [635]: x = [[[[1, 2, 3]]]]
In [636]: x[0]\
...: [0]\
...: [0]\
...: [0]
Out[636]: 1
This seems like the easiest and cleanest way to do it.
Don't use exec
unless you have to. Actually, don't use it, ever.
In some cases, keeping a reference to a sub dict works if you are to frequently visit that part of your data structure again and again. It is a matter of deciding what is the best solution to apply given the situation and circumstances.