Get component instance by its name at runtime

I am trying to set some components visibility at runtime, reading components name from a dict.
I mean, I have a dict like this:

{
  'column_panel_1':True,
  'label_1': False,
  ...
}

I want to browse dict keys and set accordingly column_panel_1.visible=True, label_1.visible=False

I tried to figure out how to get the component’s instance by their name but couldn’t find a way to do that.

Can this be done somehow?

Thanks and BR

Well… From I can think of, there are two ways of doing it.

The easiest way is to use the component itself as the key in the dict, instead of its name. You can then use the key.visible = dict.get(key) or something like that.
Edit: While you can use this in forms/modules, a dictionary like this won’t be able to be saved in a SimpleObject Column of data tables, since It couldn’t be converted as JSON. Only primitive values can be keys in dictionaries to be considered a “SimpleObject”.

The other way that (I think) it could work is to use getattr(). By using:

visibility_dict = { 'column_panel_1': True }
for key in visibility_dict:
  comp = getattr(self, key)
  comp.visible = visibility_dict.get(key)

The getattr receives 2 params: the owner and a string for the attribute.
So getattr(self, ‘column_panel_1’) = self.column_panel_1

4 Likes

Thanks Gabriel, that works perfectly!
I cannot use the component ad dictionary key since that dict is stored in a DB column

Oh yeah, I guess I should’ve asked where would you use the dict later. I edited my comment for future references.
Good that the other idea worked for you!