I'm in the process of refactoring an old script that uses a dataset to get components of various nested depths. The dataset is created at initialization, so it always precisely reflects the items that are in the Vision window.
There are two problems with this that I want to fix:
ā¢ The component list only goes three levels deep
ā¢ Later when another function uses the data, the code is structured in a way that repeats itself.
The sanitized code resembles this:
if levelSelectData == "1":
selectedComponent = root.getComponent(levelOneData)
if selectedComponent is not None:
#[Do stuff with the component here]
if levelSelectData == "2":
selectedComponent = root.getComponent(levelOneData).getComponent(levelTwoData)
if selectedComponent is not None:
#[Do the exact same stuff here]
if levelSelectData == "3":
selectedComponent = root.getComponent(levelOneData).getComponent(levelTwoData).getComponent(levelThreeData)
if selectedComponent is not None:
#[Once again we have the exact same code repeated here]
My idea was to keep the dataset that is created by the initialization script, but instead of storing a list of container names and component names with a depth index, I would actually store the full path to the component as a string and use eval to get the component by the subsequent script. The refactored code would look like this:
selectedComponent = eval(path)
if selectedComponent is not None:
#[Do stuff with the component here]
This would allow me to assemble a list of paths that are as deep as they need to be with a single column. It would also allow me to call the component later without violating the DRY programming practice. I should note that there is no editable user input for this code, so in this case, there is no risk [that I am aware of] of an injection attack with this approach, but my question is whether or not there is a better approach or practice to achieve this same functionality?