I have a class that holds an unspecified number of dicts as variables. I want to provide methods that allow the user to easily append to any of the dicts while naming the corresponding variable, without having to check whether the variable was already created. Example for my goal:
>>> c = Container()
>>> c.add_value(variable="first_dict", key="foo", value=1)
>>> c.add_value(variable="first_dict", key="bar", value=2)
>>> c.add_value(variable="second_dict", key="foo", value=2)
>>> print(c.first_dict)
{"foo":1, "bar":2)
>>> print(c.second_dict)
{"foo":2)
Currently, this is my solution:
class Container():
def __init__(self):
pass
def add_value(self, variable: str, key: Any, value: Any):
x = getattr(self, variable, {})
x[key] = value
setattr(self, variable, x)
My concern is that accessing the attribute via getattr
, then mutating it and setting it back via setattr
introduces overhead that is not necessary.
Is there a better way to write the Container.add_value()
-method? Should I approach the whole problem differently?