tidy3d icon indicating copy to clipboard operation
tidy3d copied to clipboard

More convenient updated copy of nested fields

Open tylerflex opened this issue 1 year ago • 0 comments

I think a major disadvantage of our immutability choice is that it is quite tedious to update fields deeply nested within components. For example, say I want to update the size in z of a box within the Simulation.structures. The current API requires something like

new_box = simulation.structures[i].geometry.updated_copy(size=new_size)
new_structure = simulation.structures[i].updated_copy(geometry=geometry)
new_structures = list(simulation.structures)
new_structures[i] = new_structure
new_simulation = simulation.updated_copy(structures=new_structures)

what if instead we provided a short cut, such as

new_simulation = simulation.updated_copy(size=new_size, path=f"structures/{i}/geometry")

that handled this for us?

the code would look something vaguely like

def updated_copy(self, path: str = None, **kwargs):
    if not path:
        return self.updated_copy_original(**kwargs)

    path_components = path.split("/")

    field_name = path_components[0]

    # special handling for if field name is an integer index into a tuple

    sub_component = self.getattr(field_name)
    sub_path = "/".join(path_components[1:])

    new_component = sub_component.updated_copy(path=sub_path, **kwargs)
    return self.updated_copy_original(field_name=new_component)

any comments / tools that can do this for us / concerns?

tylerflex avatar Apr 09 '24 07:04 tylerflex